// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; namespace E { public class MainClass { private static int FindLeadingComma(string s, int ix) { int res = ix; while(s[res] != ',') res--; return res; } private static int FindTrailingComma(string s, int ix) { int res = ix + 1; while(s[res] != ',') res++; return res; } private static int FindValue(string s, int ix) { int lead = FindLeadingComma(s, ix); int trail = FindTrailingComma(s, ix); return int.Parse(s.Substring(lead + 1, trail - lead - 1)); } public static string InsertValueInCommaList(string s, int val) { if(s.Length <= 1) return "," + val + ","; int low = 1; if(FindValue(s, low) > val) return "," + val + s; int high = s.Length - 2; if(FindValue(s, high) < val) return s + val + ","; while(low < high) { int piv = (low + high) / 2; int pivval = FindValue(s, piv); if(pivval < val) { low = FindTrailingComma(s, piv); } else if(pivval > val) { high = FindLeadingComma(s, piv); } else { throw new ArgumentException(val + " already in list"); } } return s.Substring(0, low + 1) + val + s.Substring(high); } public static void Main(string[] args) { Console.WriteLine(InsertValueInCommaList(",1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,", 4)); Console.WriteLine(InsertValueInCommaList(",1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,", 0)); Console.WriteLine(InsertValueInCommaList(",1,2,3,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,", 21)); Random rng = new Random(); string s = ""; for(int i = 0; i < 30; i++) { try { s = InsertValueInCommaList(s, rng.Next(100)); } catch(ArgumentException) { // ignore } } Console.WriteLine(s); Console.ReadLine(); } } }