Coding Challenge
-
Who said anything about tokenising?
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
-
Failed: 1. No formatting 2. Language Dependent 3. Too verbose
Software Kinetics Wear a hard hat it's under construction
Metro RSSNorm .net wrote:
2. Language Dependent
Nothing stated you could not use a specific language. In fact part of the point it seemed was it can be done so many different ways with different languages...
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.
-
The challenge is to remove the strings that are provided. Nothing is said about removing (or, indeed, caring about, whitespace)
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
In that case, shouldn't "cat dog monkey..." end up as " monkey..." with two leading spaces? (It might just be the HTML rendering changing two to one in your OP.)
-
Norm .net wrote:
2. Language Dependent
Nothing stated you could not use a specific language. In fact part of the point it seemed was it can be done so many different ways with different languages...
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.
-
It might be the site's HTML rendering which reduces two or more adjacent spaces to one. (I put about 10 in the last sentence but it doesn't display that way!)
-
Chris barely posted and already there is a design review, rejects from marketing, the devs want to shoot the PM. The PM is whistling nastily (Nagy you dog ... cat... horse... dog) and the mischievous ones reach for the assembler books. What we miss here is QA and we can start a death-march :laugh: EDIT-------------------------- I forgot legal as well. Legal department share its thoughts here with the assistance of the tech writers ;P
Alberto Bar-Noy --------------- “The city’s central computer told you? R2D2, you know better than to trust a strange computer!” (C3PO)
Obligatory comic: http://www.sonnyradio.com/whatthecustomerreallywanted.htm[^]
-
It might be the site's HTML rendering which reduces two or more adjacent spaces to one. (I put about 10 in the last sentence but it doesn't display that way!)
-
For Dalek Dave's benefit, I dub this the Most Unique Solution.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
-
Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stripper
{
public enum StringPoint
{
None,
Start,
End,
}
public static class StringHelpersExtensions
{
public static string RightOf(this String src, string s)
{
string ret = src;
int idx = src.IndexOf(s);
if (idx != -1)
{
ret = src.Substring(s.Length);
}
return ret;
}
public static string LeftOfRightmostOf(this String src, string s)
{
string ret = src;
int idx = src.LastIndexOf(s);
if (idx != -1)
{
ret = src.Substring(0, idx);
}
return ret;
}
public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
{
bool ret = false;
whichEnd = StringPoint.None;
match = String.Empty;
foreach (string item in items)
{
if (src.StartsWith(item))
{
match = item;
whichEnd = StringPoint.Start;
ret = true;
break;
}
if (src.EndsWith(item))
{
match = item;
whichEnd = StringPoint.End;
ret = true;
break;
}
}
return ret;
}
}
class Program
{
static void Main(string[] args)
{
string input = "dog cat monkey dog horse dog";
string[] stripOf = { "dog", "cat" };
string desiredOutput = " monkey dog horse ";
string result = Stripper(input, stripOf);
if (result == desiredOutput)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail! '" + result + "'");
}
}
static string Stripper(string input, string[] stripOf)
{
string ret = input;
string match;
StringPoint whichEnd;
string test = ret.Trim();
string leftPad = String.Empty;
string rightPad = String.Empty;
while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
{
switch (whichEnd)
{
case StringPoint.Start:
// The result always preserves the leading space separating the token, so add it back in.
leftPad = " ";
ret = leftPad + test.RightOf(match).Trim() + rightPad;
break;
case StringPoint.End:
// The result always preserves -
You can think it means whatever you want, but in correct English usage either can mean both 'one of two' or 'each of two.
Every man can tell how many goats or sheep he possesses, but not how many friends.
ChrisElston wrote:
'each of two.
That is "both", not "either". Don't use a word for two meanings when there is already a word for the other. You want to ride a see-saw -- you may sit at either end.
-
Being a programmer, I cannot resist a coding challenge. Do not misconstrue this to be a general lifting of my personal CodeProject boycott. Usage:
string text = "dog cat dog doghorse monkey dog fishcat dog cat";
string[] removers = new string[] {"cat", "dog"};
do
{
} while (Challenge(ref text, removers));Method:
//-----------------------------------------------------------------------
private bool Challenge(ref string text, string[] removeThese)
{
bool changed = false;
for (int i = 0; i < removeThese.Length; i++)
{
string target = removeThese[i];
int start = -1;
int end = -1;
do
{
end = (text.StartsWith(target)) ? target.Length : -1;
if (end > -1)
{
text = text.Substring(end);
changed = true;
}
text = text.Trim();
} while (end > -1);
do
{
start = (text.EndsWith(target)) ? text.Length - target.Length : -1;
if (start > -1)
{
text = text.Substring(0, start);
changed = true;
}
text = text.Trim();
} while (start > -1);
}
return changed;
}You can also easily make this a recursive method.
".45 ACP - because shooting twice is just silly" - JSOP, 2010
-----
You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
-----
"Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997Did you actually test this? The resulting string needs to preserve any leading and/or trailing spaces after removing the token. Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
Not "either alive and dead"? ;) In any case, the cat is itself an observer, so the waveform is always collapsed to a known state or "alive" or "dead", so it's a silly thought experiment (IMHO).
A dead cat knows it's dead? :confused:
-
Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
I'll be the first to put up the recursive solution in C#.
private string TrimCatDog(string input)
{
if (input.StartsWith(" ") || input.EndsWith(" "))
return TrimCatDog(input.Trim());
if (input.StartsWith("cat") || input.StartsWith("dog"))
return TrimCatDog(input.Substring(3));
if (input.EndsWith("cat") || input.EndsWith("dog"))
return TrimCatDog(input.Substring(0, input.Length - 3));
return input;
} -
Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stripper
{
public enum StringPoint
{
None,
Start,
End,
}
public static class StringHelpersExtensions
{
public static string RightOf(this String src, string s)
{
string ret = src;
int idx = src.IndexOf(s);
if (idx != -1)
{
ret = src.Substring(s.Length);
}
return ret;
}
public static string LeftOfRightmostOf(this String src, string s)
{
string ret = src;
int idx = src.LastIndexOf(s);
if (idx != -1)
{
ret = src.Substring(0, idx);
}
return ret;
}
public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
{
bool ret = false;
whichEnd = StringPoint.None;
match = String.Empty;
foreach (string item in items)
{
if (src.StartsWith(item))
{
match = item;
whichEnd = StringPoint.Start;
ret = true;
break;
}
if (src.EndsWith(item))
{
match = item;
whichEnd = StringPoint.End;
ret = true;
break;
}
}
return ret;
}
}
class Program
{
static void Main(string[] args)
{
string input = "dog cat monkey dog horse dog";
string[] stripOf = { "dog", "cat" };
string desiredOutput = " monkey dog horse ";
string result = Stripper(input, stripOf);
if (result == desiredOutput)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail! '" + result + "'");
}
}
static string Stripper(string input, string[] stripOf)
{
string ret = input;
string match;
StringPoint whichEnd;
string test = ret.Trim();
string leftPad = String.Empty;
string rightPad = String.Empty;
while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
{
switch (whichEnd)
{
case StringPoint.Start:
// The result always preserves the leading space separating the token, so add it back in.
leftPad = " ";
ret = leftPad + test.RightOf(match).Trim() + rightPad;
break;
case StringPoint.End:
// The result always preservesMarc Clifton wrote:
There's probably a regex solution, but that's gross.
Glad to be of service to you ;P
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;namespace StripWords
{
static class Program
{
static void Main()
{
String input, replace;
input = replace = "dog cat monkey dog horse dog";
String stripThese = "dog cat";
String[] words = stripThese.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
String strRegEx = String.Empty;
foreach (String word in words)
{
strRegEx = strRegEx + String.Format(@"^\s*{0}\s*|\s*{0}\s*$|", word);
}
strRegEx = strRegEx.Trim(new char[] { '|' });
Regex trimRegExp = new Regex(strRegEx);bool replaceNeeded = false; do { if (replaceNeeded = trimRegExp.Match(replace).Length > 0) { replace = trimRegExp.Replace(replace, ""); } } while (replaceNeeded); Console.WriteLine("Trimming \\"{0}\\" from input \\"{1}\\" yields \\"{2}\\"!", stripThese, input, replace); Console.ReadLine(); } }
}
Cheers! :)
"With sufficient thrust, pigs fly just fine."
Ross Callon, The Twelve Networking Truths, RFC1925
-
My approach is to use substring to grab the current end and starting strings. Substring is also used to update the result. I am sure there are some faster ways, but this approach is very clean IMO.
public string Parse(string input, List remove)
{
string result = input.Trim();
bool startRemoved;
bool endRemoved;do { startRemoved = false; endRemoved = false; foreach (var match in remove) { //Determine if the remove string is fitable with in the remaining output bool inRange = result.Length >= match.Length; //Capture the beginning and ending characters string beginning = result.Substring(0, match.Length); string end = result.Substring(result.Length - match.Length, match.Length); if (inRange && beginning.Equals(match)) { //Update the result with the matched section removed result = result.Substring(match.Length, result.Length - match.Length).TrimStart(); startRemoved = true; } if (inRange && end.Equals(match)) { //Update the result with the matched section removed result = result.Substring(0, result.Length - match.Length).TrimEnd(); endRemoved = true; } } } while (startRemoved || endRemoved); return result;
}
[Edit] Added a do while. The do while shuts down if nothing is removed. If anything is removed it must go back and check the removal collection. Optimization could be to track which is removed to then check up to that point. E.g. "dog" "cat" and "monkey" are to be removed (and collection is in that order). If "cat" is removed (start or end), then "monkey" will be checked on active foreach. "dog" and "cat" are the only ones that need be checked on the next do while iteration (unless one of them removes another character set) [Edit] Added Trimmers.
Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.
Collin Jasnoch wrote:
but this approach is very clean IMO.
But won't work, right? The desired result is " monkey dog horse " Did you notice the leading and trailing spaces? ;) Plus, your result calculation doesn't take into account that the result will have a leading or trailing space in it, just resulting in a failure for the next calculation of beginning and end. Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
Marc Clifton wrote:
There's probably a regex solution, but that's gross.
Glad to be of service to you ;P
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;namespace StripWords
{
static class Program
{
static void Main()
{
String input, replace;
input = replace = "dog cat monkey dog horse dog";
String stripThese = "dog cat";
String[] words = stripThese.Split(new Char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
String strRegEx = String.Empty;
foreach (String word in words)
{
strRegEx = strRegEx + String.Format(@"^\s*{0}\s*|\s*{0}\s*$|", word);
}
strRegEx = strRegEx.Trim(new char[] { '|' });
Regex trimRegExp = new Regex(strRegEx);bool replaceNeeded = false; do { if (replaceNeeded = trimRegExp.Match(replace).Length > 0) { replace = trimRegExp.Replace(replace, ""); } } while (replaceNeeded); Console.WriteLine("Trimming \\"{0}\\" from input \\"{1}\\" yields \\"{2}\\"!", stripThese, input, replace); Console.ReadLine(); } }
}
Cheers! :)
"With sufficient thrust, pigs fly just fine."
Ross Callon, The Twelve Networking Truths, RFC1925
FAIL! ;) You're not preserving the leading and/or trailing space in the result after removing a token from the beginning or end. But cool none-the-less, and probably solvable, right? Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
Every sofware project starts with making a plan with strict schedules about deliverables and defining the architectural artefacts. We need to set up a scrum meeting about choosing the appropriate platform and team composition. We could do this sometimes next week, please send me your suggestions matching your schedules. Attached is the invoice for the 25% of the estimated project costs.
-
Dang, what are we, a bunch of whiners? It's a PROGRAMMING CHALLENGE! START YOUR CODING ENGINES!!! Do we need detail specs? Hell NO!!! There's probably a regex solution, but that's gross. Here's something I whipped together in about 15 minutes (took a bit of debugging, a few nuances to it) that I hope readable and somewhat reusable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Stripper
{
public enum StringPoint
{
None,
Start,
End,
}
public static class StringHelpersExtensions
{
public static string RightOf(this String src, string s)
{
string ret = src;
int idx = src.IndexOf(s);
if (idx != -1)
{
ret = src.Substring(s.Length);
}
return ret;
}
public static string LeftOfRightmostOf(this String src, string s)
{
string ret = src;
int idx = src.LastIndexOf(s);
if (idx != -1)
{
ret = src.Substring(0, idx);
}
return ret;
}
public static bool StartsOrEndsWith(this String src, string[] items, out string match, out StringPoint whichEnd)
{
bool ret = false;
whichEnd = StringPoint.None;
match = String.Empty;
foreach (string item in items)
{
if (src.StartsWith(item))
{
match = item;
whichEnd = StringPoint.Start;
ret = true;
break;
}
if (src.EndsWith(item))
{
match = item;
whichEnd = StringPoint.End;
ret = true;
break;
}
}
return ret;
}
}
class Program
{
static void Main(string[] args)
{
string input = "dog cat monkey dog horse dog";
string[] stripOf = { "dog", "cat" };
string desiredOutput = " monkey dog horse ";
string result = Stripper(input, stripOf);
if (result == desiredOutput)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail! '" + result + "'");
}
}
static string Stripper(string input, string[] stripOf)
{
string ret = input;
string match;
StringPoint whichEnd;
string test = ret.Trim();
string leftPad = String.Empty;
string rightPad = String.Empty;
while (test.StartsOrEndsWith(stripOf, out match, out whichEnd))
{
switch (whichEnd)
{
case StringPoint.Start:
// The result always preserves the leading space separating the token, so add it back in.
leftPad = " ";
ret = leftPad + test.RightOf(match).Trim() + rightPad;
break;
case StringPoint.End:
// The result always preserves -
Hmmmm, 2 KISS algorithms A two pass algorithm might be: 1.) Tokenize the string using white space characters. 2.) Moving from left to right, push the string into a deque if the string is not in the excluded list. If we encounter a string that is included, all proceeding tags are pushed into the deque. 3.) Then do the same from right to left. A single pass algorithm might be: 1.) Tokenize the string using white space characters. 2.) Push all tags into a pair of string:index 3.) For each pair of string and index, if the string is excluded... if the index value of all other string:index pairs before me are also excluded... My index is the beginning of the string. 4.) For each pair of string and index, if the string is excluded... if the index value of all other string:index pairs after me are also excluded... My index is the end of the string. :) I'm too lazy to write the code. Btw, I think the single pass algorithm could be implemented in a single lambda line of code. Best Wishes, -David Delaune
Now remove "the cat" from the string.
-
Back in the Days of Yore we had a couple of small coding challenges such as the Lean and Mean comp. I was thinking that there are a ton of small, well defined problems that can be tackled a zillion ways in a zillion languages and that it would be cool to see what you guys can come up with. I'd like to start the ball rolling with the following simple task: Problem: Given a string of text, trim from each end of the text each all occurrences of a given set of strings Sample input: Input string: "dog cat monkey dog horse dog" Strings that need to be trimmed from each end: { "dog", "cat" } Final output should be: " monkey dog horse" Final output should be " cat monkey dog horse " [Edit: My final sample output was incorrect, so to be fair I'll accept either answer] It's up to you whether you worry about case sensitivity. Let's see who can provide the smallest, neatest most elegant, most unique and/or fastest code. For those who feel like jumping on the "No Programming questions" bandwagon, please re-read the lounge guidelines. The point of this is to have fun, not to solve each other's programming issues.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
Here's my stab at a solution in C#: [Edit: Chris updated the guidance, and I changed the method accordingly.]
public static string CPtrimmer(string input, string[] trims, StringComparison compare = StringComparison.InvariantCultureIgnoreCase)
{
String Input = input;foreach (var trimWord in trims) { if (Input.StartsWith(trimWord, compare)) Input = Input.Remove(Input.IndexOf(trimWord, compare), trimWord.Length); if (Input.EndsWith(trimWord, compare)) Input = Input.Remove(Input.LastIndexOf(trimWord, compare), trimWord.Length); } if (Input != input) return CPtrimmer(Input, trims); else return Input;
}
[modified] Given the exchange below, I am including the usage of this method as well (console C#):
static void Main(string[] args)
{
String input = "dog cat monkey dog horse dog";
String[] trims = new String[] { "dog", "cat" };String result = CPtrimmer(input, trims); // After CPtrimmer has returned, the result is " cat monkey dog horse "
}
Be The Noise