private bool SortNodes(StringComparison stringComparison) { var comparer = new DelegateComparer <string>((left, right) => string.Compare(left, right, stringComparison)); var nodes = _documentRoot .Elements(_dataNodeName) .ToArray(); var sortedNodes = nodes .OrderBy(node => node.Attribute(_nameAttributeName)?.Value.TrimStart('>') ?? string.Empty, comparer) .ToArray(); if (nodes.SequenceEqual(sortedNodes)) { return(false); } foreach (var item in nodes) { Contract.Assume(item != null); item.Remove(); } foreach (var item in sortedNodes) { _documentRoot.Add(item); } return(true); }
public MouseInputObservable(IButtonActionEvaluator actionEvaluator) { _actionEvaluator = actionEvaluator; var delegateComparer = new DelegateComparer(); _mouseButtonDictionary = new MultiValueDictionary<MouseButton, Action>(delegateComparer); }
public static void Main(String[] args) { SCG.IComparer <Rec <string, int> > lexico1 = new Lexico(); SCG.IComparer <Rec <string, int> > lexico2 = new DelegateComparer <Rec <string, int> >( delegate(Rec <string, int> item1, Rec <string, int> item2) { int major = item1.X1.CompareTo(item2.X1); return(major != 0 ? major : item1.X2.CompareTo(item2.X2)); }); Rec <String, int> r1 = new Rec <String, int>("Carsten", 1962); Rec <String, int> r2 = new Rec <String, int>("Carsten", 1964); Rec <String, int> r3 = new Rec <String, int>("Christian", 1932); Console.WriteLine(lexico1.Compare(r1, r1) == 0); Console.WriteLine(lexico1.Compare(r1, r2) < 0); Console.WriteLine(lexico1.Compare(r2, r3) < 0); Console.WriteLine(lexico2.Compare(r1, r1) == 0); Console.WriteLine(lexico2.Compare(r1, r2) < 0); Console.WriteLine(lexico2.Compare(r2, r3) < 0); SCG.IComparer <String> rev = ReverseComparer <String>(Comparer <String> .Default); Console.WriteLine(rev.Compare("A", "A") == 0); Console.WriteLine(rev.Compare("A", "B") > 0); Console.WriteLine(rev.Compare("B", "A") < 0); }
public void Contains_ComparerAlwaysReturnsEqual_ReturnsTrue(int min, int max, int value) { var comparer = new DelegateComparer <int>((x, y) => 0); var uut = new MinMaxPair <int>(min, max, comparer); uut.Contains(value).ShouldBeTrue(); }
public void Contains_ComparerAlwaysReturnsLessThan_ReturnsFalse(int min, int max, int value) { var comparer = new DelegateComparer <int>((x, y) => - 1); var uut = new MinMaxPair <int>(min, max, comparer); uut.Contains(value).ShouldBeFalse(); }
private bool SortAndAdd(StringComparison stringComparison, [CanBeNull] XElement newNode) { var comparer = new DelegateComparer <string>((left, right) => string.Compare(left, right, stringComparison)); string GetName(XElement node) => node.Attribute(_nameAttributeName)?.Value.TrimStart('>') ?? string.Empty; var nodes = _documentRoot .Elements(_dataNodeName) .ToArray(); var sortedNodes = nodes .OrderBy(node => GetName(node), comparer) .ToArray(); var hasContentChanged = SortNodes(nodes, sortedNodes); if (newNode == null) { return(hasContentChanged); } var newNodeName = GetName(newNode); var nextNode = sortedNodes.FirstOrDefault(node => comparer.Compare(GetName(node), newNodeName) > 0); if (nextNode != null) { nextNode.AddBeforeSelf(newNode); } else { _documentRoot.Add(newNode); } return(true); }
public void Test() { // Test a senseless comparison operator. var c = new DelegateComparer <int>((x, y) => x + y); Assert.AreEqual(10, c.Compare(3, 7)); }
/// <summary> /// Sorts two-dimensional array using IComparer.Sort method. /// </summary> /// <param name="arr">Array to sort.</param> /// <param name="comparer">IComparer.Sort delegate.</param> public static void Sort(this int[][] arr, DelegateComparer comparer) { _ = arr ?? throw new ArgumentNullException(nameof(arr), "Array should not be null."); _ = comparer ?? throw new ArgumentNullException(nameof(comparer), "Comparer should not be null."); // Call method with interface. Sort(arr, new Adapter(comparer)); }
public MouseInputObservable(IButtonActionEvaluator actionEvaluator) { _actionEvaluator = actionEvaluator; var delegateComparer = new DelegateComparer(); _mouseButtonDictionary = new MultiValueDictionary <MouseButton, Action>(delegateComparer); }
public void CompareTo_NonGeneric_ComparerAlwaysReturns0_Returns0(int xMin, int xMax, int yMin, int yMax) { var comparer = new DelegateComparer <int>((x, y) => 0); var uut1 = new MinMaxPair <int>(xMin, xMax, comparer); var uut2 = new MinMaxPair <int>(yMin, yMax, comparer); uut1.CompareTo((object)uut2).ShouldBe(0); }
public void Equals_Generic_ComparerAlwaysReturnsNegative1_ReturnsFalse(int xMin, int xMax, int yMin, int yMax) { var comparer = new DelegateComparer <int>((x, y) => - 1); var uut1 = new MinMaxPair <int>(xMin, xMax, comparer); var uut2 = new MinMaxPair <int>(yMin, yMax, comparer); uut1.Equals(uut2).ShouldBeFalse(); }
public void Equals_NonGeneric_ComparerAlwaysReturnsNegative1_ReturnsNegative1(int xMin, int xMax, int yMin, int yMax) { var comparer = new DelegateComparer <int>((x, y) => - 1); var uut1 = new MinMaxPair <int>(xMin, xMax, comparer); var uut2 = new MinMaxPair <int>(yMin, yMax, comparer); uut1.CompareTo((object)uut2).ShouldBe(-1); }
public void OperatorNotEquals_ComparerAlwaysReturnsNegative1_ReturnsTrue(int xMin, int xMax, int yMin, int yMax) { var comparer = new DelegateComparer <int>((x, y) => - 1); var uut1 = new MinMaxPair <int>(xMin, xMax, comparer); var uut2 = new MinMaxPair <int>(yMin, yMax, comparer); (uut1 != uut2).ShouldBeTrue(); }
protected override void OnCompositionContainerComposed(CompositionContainer container, IServiceProvider serviceProvider) { base.OnCompositionContainerComposed(container, serviceProvider); var conventions = this.container.Resolve <BootstrapConventions>(); var allAssemblies = new HashSet <Assembly>(); allAssemblies.Add(Assembly.GetEntryAssembly()); foreach (var dll in Directory.EnumerateFiles(Helpers.EnvironmentHelper.GetCurrentDirectory(), "*.dll")) { var name = Path.GetFileNameWithoutExtension(dll); var a = Assembly.Load(name); if (conventions.IncludeAssemblyInContainerScan(a)) { allAssemblies.Add(a); } } var comparer = new DelegateComparer <IAutofacModule>((x, y) => { var __x = x as IAutofacBuiltinModule; var __y = y as IAutofacBuiltinModule; if (__x == null && __y != null) { return(1); } if (__x != null && __y == null) { return(-1); } return(0); }); var toInstall = this.Modules.Where(i => this.ShouldInstall(i)) .OrderBy(m => m, comparer) .ToArray(); var injectViewInRegion = new InjectViewInRegionModule(conventions); var subscribeToMessageModule = new SubscribeToMessageModule(conventions); var updater = new ContainerBuilder(); updater.RegisterModule(injectViewInRegion); updater.RegisterModule(subscribeToMessageModule); foreach (var item in toInstall) { item.Configure(updater, conventions, allAssemblies); } updater.Update(this.container); injectViewInRegion.Commit(this.container); subscribeToMessageModule.Commit(this.container); }
private static Tuple <int[], double[]> ShortestPaths(IEnumerable <Tuple <int, int> > edges, Func <int, int, double> weight, int source) { var neighborsOf = edges.ToNeighborhoodLists(); var vertices = Enumerable.Range(0, neighborsOf.Count); // distanceTo will store the distance from source to any other vertex. At the beginning according to Dijkstra algorithm it's infinity for all // vertices except the source var distanceTo = Enumerable.Repeat(double.PositiveInfinity, neighborsOf.Count).ToArray(); distanceTo[source] = 0; // distance from the source to itself // previous[v] will store the previous vertex in the shortest path from source to v. Initialized to -1, which means no previous vertex // as we don't know the shortest path yet. var previous = Enumerable.Repeat(-1, neighborsOf.Count).ToArray(); var priorityQueue = new SortedSet <int>(DelegateComparer.Create <int>((x, y) => // compare vertices according to their distance from source { var weightCompare = distanceTo[x].CompareTo(distanceTo[y]); if (weightCompare == 0) { return(x.CompareTo(y)); } else { return(weightCompare); } })); foreach (var v in vertices) { priorityQueue.Add(v); } // the main loop of the Dijkstra algorithm while (priorityQueue.Count > 0) { // we remove the min-distance vertex from the priority queue var v = priorityQueue.First(); priorityQueue.Remove(v); // update all neighbors of v with new distances foreach (var u in neighborsOf[v]) { var newDistance = distanceTo[v] + weight(v, u); if (newDistance < distanceTo[u]) { // we have to add and remove u from the priority queue during distance update, otherwise the priority queue will incorrectly // return the minimal-distance node. priorityQueue.Remove(u); distanceTo[u] = newDistance; priorityQueue.Add(u); previous[u] = v; } } } return(Tuple.Create(previous, distanceTo)); }
public void Task_03_Single_Priority() { var pc = new PriorityComparer <Item>("Z"); var dc = new DelegateComparer <Item>(CompareFirstName); var c = new CompositeComparer <Item>(new IComparer <Item>[] { pc, dc }); var z = new Item("Z"); c.Compare(A, z).Should().BeGreaterThan(0); c.Compare(z, A).Should().BeLessThan(0); }
public void compare_delegates_to_comparison_method() { var comparer = new DelegateComparer<int>((x, y) => { Assert.Equal(x, 1); Assert.Equal(y, 2); return 3; }); Assert.Equal(3, comparer.Compare(1, 2)); }
public void Task_01_Compare() { var c = new DelegateComparer <string>((x, y) => string.Compare(x, y, StringComparison.Ordinal)); c.Compare(null, null).Should().Be(0); c.Compare(null, "A").Should().BeLessThan(0); c.Compare("A", null).Should().BeGreaterThan(0); c.Compare("A", "A").Should().Be(0); c.Compare("A", "B").Should().BeLessThan(0); c.Compare("B", "A").Should().BeGreaterThan(0); }
/// <summary> /// Initializes a new instance of the <see cref="BindingProvider" /> class. /// </summary> public BindingProvider(IBindingParser parser = null) { _parser = parser ?? new BindingParser(); var comparer = new DelegateComparer<IBindingSourceDecorator>((manager, targetManager) => targetManager.Priority.CompareTo(manager.Priority)); _decorators = new OrderedListInternal<IBindingSourceDecorator>(comparer); _defaultBehaviors = new OrderedListInternal<IBindingBehavior>(BehaviorComparer) { new OneWayBindingMode() }; _buildDelegate = BuildBinding; }
public void Task_05_Priority_Sort_Descending() { var pc = new PriorityComparer <Item>("Z", "Y"); var dc = new DelegateComparer <Item>(CompareFirstNameDescending); var c = new CompositeComparer <Item>(new IComparer <Item>[] { pc, dc }); var z = new Item("Z"); var y = new Item("Y"); var array = new[] { A, z, B, A1, y }; Array.Sort(array, c); array.SequenceEqual(new[] { z, y, B, A1, A }).Should().BeTrue(); }
public void Constructor_MinMax_ComparerAlwaysReturns1_ThrowsException(int min, int max) { var comparer = new DelegateComparer <int>((x, y) => 1); var result = Should.Throw <ArgumentOutOfRangeException>(() => { new MinMaxPair <int>(min, max, comparer); }); result.ParamName.ShouldBe(nameof(max)); result.ActualValue.ShouldBe(max); }
public void HashSetComparesByComparator() { var comparer = new DelegateComparer <KeyValuePair <string, string>, string>(p => p.Key); var items = new[] { new KeyValuePair <string, string>("myKey", "myValue1"), new KeyValuePair <string, string>("myKey", "myValue2"), }; int actual = new HashSet <KeyValuePair <string, string> >(items, comparer).Count; Assert.Equal(1, actual); }
/// <summary> /// Initializes a new instance of the <see cref="BindingProvider" /> class. /// </summary> public BindingProvider(IBindingParser parser = null) { _parser = parser ?? new BindingParser(); var comparer = new DelegateComparer <IBindingSourceDecorator>((manager, targetManager) => targetManager.Priority.CompareTo(manager.Priority)); _decorators = new OrderedListInternal <IBindingSourceDecorator>(comparer); _defaultBehaviors = new OrderedListInternal <IBindingBehavior>(BehaviorComparer) { new OneWayBindingMode() }; _buildDelegate = BuildBinding; }
/// public virtual System.Collections.Generic.IList<Tuple<int, float>> Recommend( int user_id, int n = -1, System.Collections.Generic.ICollection<int> ignore_items = null, System.Collections.Generic.ICollection<int> candidate_items = null) { if (candidate_items == null) candidate_items = Enumerable.Range(0, MaxItemID - 1).ToList(); if (ignore_items == null) ignore_items = new int[0]; System.Collections.Generic.IList<Tuple<int, float>> ordered_items; if (n == -1) { var scored_items = new List<Tuple<int, float>>(); foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = Predict(user_id, item_id); if (score > float.MinValue) scored_items.Add(Tuple.Create(item_id, score)); } ordered_items = scored_items.OrderByDescending(x => x.Item2).ToArray(); } else { var comparer = new DelegateComparer<Tuple<int, float>>( (a, b) => a.Item2.CompareTo(b.Item2) ); var heap = new IntervalHeap<Tuple<int, float>>(n, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(Tuple.Create(item_id, score)); if (heap.Count > n) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Item2; } } } ordered_items = new Tuple<int, float>[heap.Count]; for (int i = 0; i < ordered_items.Count; i++) ordered_items[i] = heap.DeleteMax(); } return ordered_items; }
public void Task_06_MultiLevel() { var pc = new DelegateComparer <Item>(CompareFirstName); var dc = new DelegateComparer <Item>(CompareLastName); var c = new CompositeComparer <Item>(new IComparer <Item>[] { pc, dc }); var a1 = new Item("a1", "Zhang", "A"); var b1 = new Item("b1", "Zhang", "B"); var c1 = new Item("c1", "Chen", "C"); var array = new[] { a1, b1, c1 }; Array.Sort(array, c); array.SequenceEqual(new[] { c1, a1, b1 }).Should().BeTrue(); }
public void IsInRange_ComparerAlwaysReturnsGreaterThan_ThrowsException(int min, int max) { var comparer = new DelegateComparer <int>((x, y) => 1); var @this = 0; var result = Should.Throw <ArgumentOutOfRangeException>(() => { @this.IsInRange(min, max, comparer); }); result.ParamName.ShouldBe(nameof(max)); result.ActualValue.ShouldBe(max); }
public void DistinctComparesByComparator() { var comparer = new DelegateComparer <KeyValuePair <string, string>, string>(p => p.Key); int actual = new[] { new KeyValuePair <string, string>("myKey", "myValue1"), new KeyValuePair <string, string>("myKey", "myValue2"), } .Distinct(comparer) .Count(); Assert.Equal(1, actual); }
public void ReverseSort() { var list = new List <int> { 6, 3, 4, 9, 10, 23, 66, 0, 1, 2, 45, }; var expect = new int[] { 66, 45, 23, 10, 9, 6, 4, 3, 2, 1, 0, }; var comparer = new DelegateComparer <int> { DelegateOfCompare = (x, y) => x == y ? 0 : x < y ? 1 : -1 // decending sort }; list.Sort(comparer); list.ToArray().Is(expect); }
public void LengthSort() { var list = new List <string> { "amenbo", "akaina", "aeiou", "fuji", "a", "sanroku", "oomu", "naku", }; var expect = new string[] { "a", "fuji", "oomu", "naku", "aeiou", "amenbo", "akaina", "sanroku", }; var comparer = new DelegateComparer <string> { DelegateOfCompare = (x, y) => x.Length.CompareTo(y.Length) }; list.Sort(comparer); list.ToArray().Is(expect); }
public static void Main(String[] args) { // SortedArray<Object> sarr = new SortedArray<Object>(); SCG.IComparer<Rec<string,int>> lexico = new DelegateComparer<Rec<string,int>>( delegate(Rec<string,int> r1, Rec<string,int> r2) { int order = r1.X1.CompareTo(r2.X1); return order==0 ? r1.X2.CompareTo(r2.X2) : order; }); SortedArray<Rec<string,int>> sarr = new SortedArray<Rec<string,int>>(lexico); sarr.Add(new Rec<string,int>("ole", 32)); sarr.Add(new Rec<string,int>("hans", 77)); sarr.Add(new Rec<string,int>("ole", 63)); foreach (Rec<string,int> r in sarr) Console.WriteLine(r); }
/// <summary> /// Sort jagged array using bubble sort with an IComparer a delegate /// </summary> /// <param name="arr"></param> /// <param name="comparator"></param> public static void BubbleSortBySums(int[][] arr, DelegateComparer delegateComparer) { int[] temp = new int[0]; for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length - 1; j++) { if (delegateComparer(arr[i], arr[j]) > 0) { Swap(arr[i], arr[j], temp); } } } }
private void SortNodes(StringComparison stringComparison) { var nodes = _documentRoot.Elements(_dataNodeName).ToArray(); foreach (var item in nodes) { Contract.Assume(item != null); item.Remove(); } var comparer = new DelegateComparer <string>((left, right) => string.Compare(left, right, stringComparison)); foreach (var item in nodes.OrderBy(node => node.TryGetAttribute(_nameAttributeName).TrimStart('>'), comparer)) { _documentRoot.Add(item); } }
/// <summary> /// Sorts the source collection using custom sort criteria. /// </summary> /// <remarks> /// Please note that your compare function needs to take care about /// proper conversion of types to be comparable! /// </remarks> /// <param name="source"> /// The source collection to sort. /// </param> /// <param name="args"> /// Sort criteria to use. /// </param> /// <returns> /// A sorted array containing collection elements. /// </returns> public object Execute(ICollection source, object[] args) { if (source == null || source.Count == 0) { return(source); } if (args == null || args.Length != 1) { throw new ArgumentException("compare expression is a required argument for orderBy"); } var arg = args[0]; IComparer comparer = null; if (arg is string) { var expCompare = Expression.Parse((string)arg); comparer = new SimpleExpressionComparer(expCompare); } else if (arg is IComparer) { comparer = (IComparer)arg; } else if (arg is LambdaExpressionNode) { var fnCompare = (LambdaExpressionNode)arg; if (fnCompare.ArgumentNames.Length != 2) { throw new ArgumentException("compare function must accept 2 arguments"); } comparer = new LambdaComparer(fnCompare); } else if (arg is Delegate) { comparer = new DelegateComparer((Delegate)arg); } AssertUtils.ArgumentNotNull(comparer, "comparer", "orderBy(comparer) argument 'comparer' does not evaluate to a supported type"); var list = new ArrayList(source); list.Sort(comparer); return(list); }
public static void Main(String[] args) { // SortedArray<Object> sarr = new SortedArray<Object>(); SCG.IComparer <Rec <string, int> > lexico = new DelegateComparer <Rec <string, int> >( delegate(Rec <string, int> r1, Rec <string, int> r2) { int order = r1.X1.CompareTo(r2.X1); return(order == 0 ? r1.X2.CompareTo(r2.X2) : order); }); SortedArray <Rec <string, int> > sarr = new SortedArray <Rec <string, int> >(lexico); sarr.Add(new Rec <string, int>("ole", 32)); sarr.Add(new Rec <string, int>("hans", 77)); sarr.Add(new Rec <string, int>("ole", 63)); foreach (Rec <string, int> r in sarr) { Console.WriteLine(r); } }
public void Task_03_Single_Descending(Item x, Item y, bool?result) { var dc = new DelegateComparer <Item>(CompareFirstNameDescending); var c = new CompositeComparer <Item>(new[] { dc }); var v = c.Compare(x, y); if (v == 0) { result.Should().BeNull(); return; } if (v < 0) { result.Should().BeTrue(); return; } result.Should().BeFalse(); }
/// <summary>Score items for a given user</summary> /// <param name="recommender">the recommender to use</param> /// <param name="user_id">the numerical ID of the user</param> /// <param name="candidate_items">a collection of numerical IDs of candidate items</param> /// <param name="n">number of items to return (optional)</param> /// <returns>a list of pairs, each pair consisting of the item ID and the predicted score</returns> public static System.Collections.Generic.IList<Pair<int, float>> ScoreItems(this IRecommender recommender, int user_id, System.Collections.Generic.IList<int> candidate_items, int n = -1) { if (n == -1) { var result = new Pair<int, float>[candidate_items.Count]; for (int i = 0; i < candidate_items.Count; i++) { int item_id = candidate_items[i]; result[i] = new Pair<int, float>(item_id, recommender.Predict(user_id, item_id)); } return result; } else { var comparer = new DelegateComparer<Pair<int, float>>( (a, b) => a.Second.CompareTo(b.Second) ); var heap = new IntervalHeap<Pair<int, float>>(n, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) { float score = recommender.Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(new Pair<int, float>(item_id, score)); if (heap.Count > n) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Second; } } } var result = new Pair<int, float>[heap.Count]; for (int i = 0; i < result.Length; i++) result[i] = heap.DeleteMax(); return result; } }
public void SetUp() { _comparer = new DelegateComparer(); }
public void Test() { // Test a senseless comparison operator. var c = new DelegateComparer<int>((x, y) => x + y); Assert.AreEqual(10, c.Compare(3, 7)); }
/// <summary> /// Sorts the source collection using custom sort criteria. /// </summary> /// <remarks> /// Please note that your compare function needs to take care about /// proper conversion of types to be comparable! /// </remarks> /// <param name="source"> /// The source collection to sort. /// </param> /// <param name="args"> /// Sort criteria to use. /// </param> /// <returns> /// A sorted array containing collection elements. /// </returns> public object Process(ICollection source, object[] args) { if (source == null || source.Count == 0) { return source; } if (args == null || args.Length != 1) { throw new ArgumentException("compare expression is a required argument for orderBy"); } object arg = args[0]; IComparer comparer = null; if (arg is string) { IExpression expCompare = Expression.Parse((string) arg); comparer = new SimpleExpressionComparer(expCompare); } else if (arg is IComparer) { comparer = (IComparer) arg; } else if (arg is LambdaExpressionNode) { LambdaExpressionNode fnCompare = (LambdaExpressionNode)arg; if (fnCompare.ArgumentNames.Length != 2) { throw new ArgumentException("compare function must accept 2 arguments"); } comparer = new LambdaComparer(fnCompare); } else if (arg is Delegate) { comparer = new DelegateComparer((Delegate) arg); } AssertUtils.ArgumentNotNull(comparer, "comparer", "orderBy(comparer) argument 'comparer' does not evaluate to a supported type"); ArrayList list = new ArrayList(source); list.Sort(comparer); return list; }
/// <summary>Write item predictions (scores) to a TextWriter object</summary> /// <param name="recommender">the <see cref="IRecommender"/> to use for making the predictions</param> /// <param name="user_id">ID of the user to make recommendations for</param> /// <param name="candidate_items">list of candidate items</param> /// <param name="ignore_items">list of items for which no predictions should be made</param> /// <param name="num_predictions">the number of items to return per user, -1 if there should be no limit</param> /// <param name="writer">the <see cref="TextWriter"/> to write to</param> /// <param name="user_mapping">an <see cref="IEntityMapping"/> object for the user IDs</param> /// <param name="item_mapping">an <see cref="IEntityMapping"/> object for the item IDs</param> public static void WritePredictions( this IRecommender recommender, int user_id, System.Collections.Generic.IList<int> candidate_items, System.Collections.Generic.ICollection<int> ignore_items, int num_predictions, TextWriter writer, IEntityMapping user_mapping, IEntityMapping item_mapping) { System.Collections.Generic.IList<Pair<int, float>> ordered_items; if (user_mapping == null) user_mapping = new IdentityMapping(); if (item_mapping == null) item_mapping = new IdentityMapping(); if (num_predictions == -1) { var scored_items = new List<Pair<int, float>>(); foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = recommender.Predict(user_id, item_id); if (score > float.MinValue) scored_items.Add(new Pair<int, float>(item_id, score)); } ordered_items = scored_items.OrderByDescending(x => x.Second).ToArray(); } else { var comparer = new DelegateComparer<Pair<int, float>>( (a, b) => a.Second.CompareTo(b.Second) ); var heap = new IntervalHeap<Pair<int, float>>(num_predictions, comparer); float min_relevant_score = float.MinValue; foreach (int item_id in candidate_items) if (!ignore_items.Contains(item_id)) { float score = recommender.Predict(user_id, item_id); if (score > min_relevant_score) { heap.Add(new Pair<int, float>(item_id, score)); if (heap.Count > num_predictions) { heap.DeleteMin(); min_relevant_score = heap.FindMin().Second; } } } ordered_items = new Pair<int, float>[heap.Count]; for (int i = 0; i < ordered_items.Count; i++) ordered_items[i] = heap.DeleteMax(); } writer.Write("{0}\t[", user_mapping.ToOriginalID(user_id)); if (ordered_items.Count > 0) { writer.Write("{0}:{1}", item_mapping.ToOriginalID(ordered_items[0].First), ordered_items[0].Second.ToString(CultureInfo.InvariantCulture)); for (int i = 1; i < ordered_items.Count; i++) { int item_id = ordered_items[i].First; float score = ordered_items[i].Second; writer.Write(",{0}:{1}", item_mapping.ToOriginalID(item_id), score.ToString(CultureInfo.InvariantCulture)); } } writer.WriteLine("]"); }