logo
down
shadow

Fast way to find the first unused key in a SortedDictionary?


Fast way to find the first unused key in a SortedDictionary?

By : user2948377
Date : November 14 2020, 04:51 PM
wish help you to fix your issue So, If I understand you correctly, the keys can be anywhere from 0 to int.MaxValue. In that case, you have to find the first "hole" in the sequence of keys.
This should do the job efficiently:
code :
public static int GetFirstUnusedKey<TValue>(SortedDictionary<int, TValue> dict)
{
    if (dict.Comparer != Comparer<int>.Default)
        throw new NotSupportedException("Unsupported comparer");

    using (var enumerator = dict.GetEnumerator())
    {
        if (!enumerator.MoveNext())
            return 0;

        var nextKeyInSequence = enumerator.Current.Key + 1;

        if (nextKeyInSequence < 1)
            throw new InvalidOperationException("The dictionary contains keys less than 0");

        if (nextKeyInSequence != 1)
            return 0;

        while (enumerator.MoveNext())
        {
            var key = enumerator.Current.Key;
            if (key > nextKeyInSequence)
                return nextKeyInSequence;

            ++nextKeyInSequence;
        }

        return nextKeyInSequence;
    }
}


Share : facebook icon twitter icon
SortedDictionary<TKey, TValue>: check if contents equal to another SortedDictionary?

SortedDictionary<TKey, TValue>: check if contents equal to another SortedDictionary?


By : kahlersd
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further You will have to be prepared to loop through them all, but there are important short-cuts you can test for first.
First short-cut, is to check for object identity. While "A is A" isn't quite as profound as Ayn Rand seems to think, it is a handy way to make equality code faster. Identity always entails equality, and it is common in real code to end up comparing something to itself (esp in collection look-ups, loops and where an object is passed through several layers of code).
code :
public static bool EqualSortedDict<K, V>(SortedDictionary<K, V> x, SortedDictionary<K, V> y)
{
  if(ReferenceEquals(x, y))
    return true;
  if(ReferenceEquals(x, null) || ReferenceEquals(y, null))
    return false; //both being null already hit above.
  if(x.Count != y.Count)
    return false;
  if(!x.Comparer.Equals(y.Comparer))
    return false;//check if this is what you need. Probably is but might
                 //not be in some cases.
  foreach(KeyValuePair<K, V> kvp in x)
  {
    V cmpValue = default(V);
    if(!y.TryGetValue(kvp.Key, out cmpValue) || !kvp.Value.Equals(cmpValue))
      return false;
  }
  return true;
}
How to remove every second element of a SortedDictionary as fast as possible?

How to remove every second element of a SortedDictionary as fast as possible?


By : user3270319
Date : March 29 2020, 07:55 AM
This might help you I've to remove every second element from a SortedDictionary as fast as possible. The dictionary (SortedDictionary>) can have up to 20'000 elements. So I came up with this solution: , I doubt it, because you either need to:
Find key with max value from SortedDictionary?

Find key with max value from SortedDictionary?


By : pooitoi
Date : March 29 2020, 07:55 AM
will help you If dict is your SortedDictionary<,> and you want all the keys that correspond to the max value, first check that dict is not null or empty (you need at least one element). Then maybe this works:
code :
var max = dict.Values.Max();
var relevantKeys = dict.Where(pair => max.Equals(pair.Value))
    .Select(pair => pair.Key);
C# - How to find all items in SortedDictionary which have similar keys?

C# - How to find all items in SortedDictionary which have similar keys?


By : Darren O'Donnell
Date : March 29 2020, 07:55 AM
hope this fix your issue Unfortunately in this case you need to iterate over the whole collection and select the items that match your criteria (so not much use of the dictionary itself):
code :
public IList<int> FindValues(int row, int col)
{
    myDictionary
        .Where(item => MatchKey(item.Key, row, col))
        .Select(item => item.Value)
        .ToList();
}

public bool MatchKey(string key, int row, int col)
{
    var splitKey = key.Split();
    return splitKey[1] == row.ToString() && splitKey[2] == col.ToString();
    // or match the key according to your logic
}
Dictionary<Coord, IList<int>> myDict;
class Coord
{
    public int Row { get; set; }
    public int Column { get; set; }
}
How to compare values from one SortedDictionary to Add them to a new SortedDictionary?

How to compare values from one SortedDictionary to Add them to a new SortedDictionary?


By : user2679047
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Here is an incomplete attempt using LINQ to obtain two sequences, one for enumerating forward (starting from the max item) and one for enumerating backward. After that point it is not easy to continue with LINQ, because the two sequences must be enumerated parallely in a complex way, so I went with a while loop.
code :
var mainsd = new SortedDictionary<double, int>()
{
    {500.10, 500}, {500.09, 1000}, {500.08, 2000}, {500.07, 3000},
    {500.06, 4500}, {500.05, 5500}, {500.04, 6000}, {500.03, 7000},
    {500.02, 8500}, {500.01, 9500}, {500.00, 10000}, {499.99, 9000},
    {499.98, 8000}, {499.97, 7500}, {499.96, 6500}, {499.95, 5000},
    {499.94, 4000}, {499.93, 3500}, {499.92, 2500}, {499.91, 1500},
    {499.90, 550},
};
var maxValue = mainsd.Max(e => e.Value);
var maxItemKey = mainsd.First(e => e.Value == maxValue).Key;
var forward = mainsd.SkipWhile(e => e.Key <= maxItemKey).ToArray();
var backward = mainsd.TakeWhile(e => e.Key < maxItemKey).Reverse().ToArray();
int i1 = 0;
int i2 = 0;
while (true)
{
    var sum1 = i1 < forward.Length - 1 ? forward[i1].Value + forward[i1 + 1].Value : 0;
    var sum2 = i2 < backward.Length - 1 ? backward[i2].Value + backward[i2 + 1].Value : 0;
    if (sum1 == 0 && sum2 == 0) break;
    if (sum1 >= sum2)
    {
        Console.WriteLine($"Forward:  {sum1}, Keys: {forward[i1].Key}, {forward[i1 + 1].Key}");
        i1 += 2;
    }
    else
    {
        Console.WriteLine($"Backward: {sum2}, Keys: {backward[i2 + 1].Key}, {backward[i2].Key}");
        i2 += 2;
    }
}
Forward:  18000, Keys: 500,01, 500,02
Backward: 17000, Keys: 499,98, 499,99
Backward: 14000, Keys: 499,96, 499,97
Forward:  13000, Keys: 500,03, 500,04
Forward:  10000, Keys: 500,05, 500,06
Backward: 9000, Keys: 499,94, 499,95
Backward: 6000, Keys: 499,92, 499,93
Forward:  5000, Keys: 500,07, 500,08
Backward: 2050, Keys: 499,9, 499,91
Forward:  1500, Keys: 500,09, 500,1
var valuesd = new SortedDictionary<double, int>();
valuesd.Add(forward[i1].Key, forward[i1].Value);
valuesd.Add(forward[i1 + 1].Key, forward[i1 + 1].Value);
valuesd.Add(backward[i2].Key, backward[i2].Value);
valuesd.Add(backward[i2 + 1].Key, backward[i2 + 1].Value);
if (valuesd.Values.Sum() >= mainsd.Values.Sum() * 50 / 100) break;
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org