blah blah blah is here! blah blah » Close

up0down
link

i have a hashtable of usernames as a key, when a user connects with the same name, i want to add a number to the end. so if "larry" joins, and another joins with the same name i want the new string to be "larry-01". if i search the hashtable, how do i keep track of the number at the end? because if 14 larry's join, and then 10 bob's join, how do i evaluate that? especially if 2 disconnect?

last answered one year ago

1 answers

up0down
link

Here's a possible way of dealing with that situation.

Basically, when adding a new user, this looks for the highest number of that user's name already present in the hashtable and adds one to it. It doesn't attempt to replace lower numbers which have previously been removed.

So, if you currently have: bob and bob-02 already in the hashtable, the next bob to be added will be bob-03, not the previously removed bob-01.

However, if you originally had: bob, bob-01 and bob-02 and then removed bob-02, the next bob to be added would also be bob-02:

using System;
using System.Collections;

class Program
{
static Hashtable ht;

static void Main()
{
ht = new Hashtable();
ht.Add("larry", 1); // say
ht.Add("bob", 2);

// usernames of next 6 users to join
string[] userNames = new string[]{"fred", "larry", "bob", "bob", "larry", "bobby"};
for(int i = 0; i < 6; i++)
{
AddUser(userNames[i], i + 3);
}

// display current users
DisplayUsers();

// remove bob-01
RemoveUser("bob-01");
// add another bob
AddUser("bob", 9);

// redisplay current users
Console.WriteLine();
DisplayUsers();
Console.ReadKey();
}

static void AddUser(string name, int value)
{
int count = 0;
string name2 = name + "-";
foreach(string key in ht.Keys)
{
if (key == name)
{
if (count == 0) count = 1;
}
else if (key.StartsWith(name2))
{
int index = key.IndexOf("-");
int number = int.Parse(key.Substring(index + 1));
if (number + 1 > count) count = number + 1;
}
}
if (count == 0)
{
ht.Add(name, value);
}
else
{
name2 += count.ToString("D2");
ht.Add(name2, value);
}
}

static void RemoveUser(string name)
{
if (ht.ContainsKey(name)) ht.Remove(name);
}

static void DisplayUsers()
{
foreach(string name in ht.Keys)
{
Console.WriteLine("{0} => {1}", name, ht[name]);
}
}

}

Feedback