c# - Simplest implementation of ClosestIndexOf -
i write c# string extension method closestindexof(char, index)
me closest index of character in string around provided index.
let's check examples input string:
0 1 2 3 4 5 01234567890123456789012345678901234567890123456789012345 -------------------------------------------------------- lorem ipsum dolor sit amet, consectetur adipiscing elit.
input string length 56 (i've added index positions start 0.
example result calls:
input.closestindexof(' ', 30); // 27 input.closestindexof(' ', 35); // 39 input.closestindexof(' ', 50); // 50 input.closestindexof(' ', 19); // 17 & 21 have same offset, return 21 input.closestindexof(' ', 60); // outofrangeexception input.closestindexof('x', 30); // -1
i've written far, needs several more tests , ugly , many conditions.
// index out of range if (index > value.length) throw new argumentoutofrangeexception(); // closest index below , above specified "index" position int below = result.lastindexof('-', index - 1); int above = result.indexof('-', index); // followed conditions
i expect problem more or less math problem/expression avoid conditions , make simpler.
this initial code work on. can see results initial code works when specific character found below , above or neither. have introduce additional conditions in cases when each of them has value -1. haven't added those, because that's i'm trying optimize.
what optimisations on initial code make shorter, better performing , having less conditions?
get occurences of search character , found_index
of occurence.
calculate distance between search_index
, found_index
.
d = abs(s - f);
keep occurence smallest distance.
Comments
Post a Comment