Coding Challenge
-
If spaces aren't counted as special characters the output should be " cat monkey dog horse " because cat isn't at the end after removing dog.
Curvature of the Mind now with 3D
As philosophers would say: "That depends on how you define the concept of END". :-D
-
Yes if you call it recursively you will remove it. That was not clear in your OP though...
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.
Again, no... the method itself is recursive, no need to call it recursively. Look at the last few lines of the method:
if (Input != input)
return CPtrimmer(Input, trims);
else
return Input;What this means is that if the mothod changed the original string in any way, it will call itself again to see if there is anything else to be removed. Otherwise, if nothing changed, then the method will return the result up the call stack.
Be The Noise
-
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
You're algorithm results in: " monkey dog horse " (two leading spaces) rather than: " monkey dog horse " It's really odd how every solution that I've seen somehow fails to take this into account (as well as the fact that after the first trim, there will be a leading or trailing space in the result.) Are we that bad at reading specs, meeting simple requirements, and testing our code? :sigh: Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
why no one used Regex? ok, this code is far from optimum, but i had no time to do it better :(
using System;
using System.Text.RegularExpressions;namespace chalenge
{
class Program
{
public static void Main(string[] args)
{
string input = "dog cat dog monkey dog horse dog";
string[] removes = { "dog", "cat" };
bool hasMore = false;
do{
hasMore = false;
for(int i =0; i < removes.Length; i++){while (Regex.IsMatch(input, @"^\\s\*" + removes\[i\] + @"\\s\*.\*")){ input = Regex.Replace(input, @"(?^\\s\*)" + removes\[i\] + @"(?\\s\*.\*)", "${w1}${w2}"); } while (Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){ input = Regex.Replace(input, @"(?.\*\\s\*)" + removes\[i\] + @"(?\\s\*$)", "${w1}${w2}"); } foreach(var item in removes){ if(Regex.IsMatch(input, @"^\\s\*" + item + @"\\s\*.\*") || Regex.IsMatch(input, @".\*\\s\*" + removes\[i\] + @"\\s\*$")){ hasMore = true; break; } } } }while(hasMore); Console.Write(input); Console.ReadKey(); } }
}
(sorry by the english, i'm brasilian...)
Results in too many leading spaces. The output should have one leading and one trailing space. Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
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)
I think what you have described is what is known as "Agile" programming methodology. best, Bill
"It is the mark of an educated mind to be able to entertain a thought without accepting it." Aristotle
-
Results in too many leading spaces. The output should have one leading and one trailing space. Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programmingthis results in too many spaces because of the input string "dog cat dog monkey dog horse dog", the original are "dog cat monkey dog horse dog", i thought it was to preserve all spaces, so "dog cat dog " would result into 3 spaces, and " dog" would result in 1 space, am i wrong?
-
You're algorithm results in: " monkey dog horse " (two leading spaces) rather than: " monkey dog horse " It's really odd how every solution that I've seen somehow fails to take this into account (as well as the fact that after the first trim, there will be a leading or trailing space in the result.) Are we that bad at reading specs, meeting simple requirements, and testing our code? :sigh: Marc
My Blog
An Agile walk on the wild side with Relationship Oriented ProgrammingAn example is not a specification... the spec says:
Quote:
Given a string of text, trim from each end of the text each all occurrences of a given set of strings
Which says nothing about removing spaces (which Chris has already mentioned in a few replies on the thread), therefore, all spaces are left alone. Examples are guidance, specifications are rules... I followed the rules*. *I do agree that 'technically', once you remove the first occurance of "dog", cat is NOT at the begining of the string, and should actually result in " cat monkey dog horse ". Though in looking at the guidance, since cat is removed, I assumed that spaces should be ignored and left alone. Although if you really wanted to get convoluted, and have the EXACT match of a single leading space, that would fundamentally change the given specification... hence my design choice. Taking an occams razor approach, is it more likely that the spec is wrong and we should have a convoluted solution to have a single leading space? Or more likely that it was a typo and Chris ment to have two leading spaces?
Be The Noise
-
The specs say nothing of trimming whitespace, and the hardcoding of "dog" and "cat" means the solution can't be reused.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
Your original spec was not very specific, and your current one still does remove whitespace along with the dog and cat strings. Here's one for the new specs:
private string TrimCatDog(string input, ICollection trimPets)
{
foreach(string nextString in trimPets)
{
if(input.TrimStart().StartsWith(nextString))
return TrimCatDog(input.TrimStart().Substring(nextString.Length), trimPets);
if (input.TrimEnd().EndsWith(nextString))
return TrimCatDog(input.TrimEnd().Substring(0, input.TrimEnd().Length - nextString.Length), trimPets);
}
return input;
} -
Again, no... the method itself is recursive, no need to call it recursively. Look at the last few lines of the method:
if (Input != input)
return CPtrimmer(Input, trims);
else
return Input;What this means is that if the mothod changed the original string in any way, it will call itself again to see if there is anything else to be removed. Otherwise, if nothing changed, then the method will return the result up the call stack.
Be The Noise
-
I have discovered a truly marvellous solution of this, which the margin of this website is too narrow to contain.
Ideological Purity is no substitute for being able to stick your thumb down a pipe to stop the water
You shouldn't be using the fluid layout then. :)
Luc Pattyn [My Articles] Nil Volentibus Arduum
-
Ah yes. Sorry for not seeing that. Very kewl :) Have a 5!
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.
Not a problem, thanks!
Be The Noise
-
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
Mix of recursion and regex
using System;
using System.Text.RegularExpressions;
namespace CPTrimmer
{
class Program
{
static void Main(string[] args)
{
string startVal = "dog cat monkey dog horse dog";
string[] toTrim = { "dog", "cat" };
Stripper(ref startVal, toTrim);
Console.WriteLine(startVal);
Console.ReadLine();
}
static void Stripper(ref string input, string[] toTrim)
{
foreach (string trimVal in toTrim)
{
Regex start = new Regex(@"\A[ ]{0,}"+trimVal);
if (start.IsMatch(input))
{
input = start.Replace(input, "");
Stripper(ref input, toTrim);
}
Regex end = new Regex(trimVal + @"[ ]{0,}\Z");
if (end.IsMatch(input))
{
input = end.Replace(input, "");
Stripper(ref input, toTrim);
}
}
}
}
} -
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 preservesQuote:
There's probably a regex solution
result = Regex.Replace("dog cat monkey dog horse dog", "^(dog|cat)*(.*?)((dog|cat)*)$", "$2",
RegexOptions.IgnoreCase | RegexOptions.SingleLine);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
Assuming strings contain chars below Unicode 32000 only, and ignoring white space details:
string[] drops=new string[]{"cat","dog"};
string s="dog cat monkey dog horse dog";
string rep=" ";
char c=(char)32000;
foreach(string drop in drops) {s=s.Replace(drop,c.ToString()); rep+=c; c++;}
s=s.Trim(rep.ToCharArray());
c=(char)32000;
foreach(string drop in drops) {s=s.Replace(c.ToString(),drop); c++;}
log(s);:zzz:
Luc Pattyn [My Articles] Nil Volentibus Arduum
-
Assuming strings contain chars below Unicode 32000 only, and ignoring white space details:
string[] drops=new string[]{"cat","dog"};
string s="dog cat monkey dog horse dog";
string rep=" ";
char c=(char)32000;
foreach(string drop in drops) {s=s.Replace(drop,c.ToString()); rep+=c; c++;}
s=s.Trim(rep.ToCharArray());
c=(char)32000;
foreach(string drop in drops) {s=s.Replace(c.ToString(),drop); c++;}
log(s);:zzz:
Luc Pattyn [My Articles] Nil Volentibus Arduum
:thumbsup: Neat, but lots and lots of new objects created.
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
-
You're algorithm results in: " monkey dog horse " (two leading spaces) rather than: " monkey dog horse " It's really odd how every solution that I've seen somehow fails to take this into account (as well as the fact that after the first trim, there will be a leading or trailing space in the result.) Are we that bad at reading specs, meeting simple requirements, and testing our code? :sigh: Marc
My Blog
An Agile walk on the wild side with Relationship Oriented ProgrammingChris updated the guidance, and I have changed my solution accordingly.
Be The Noise
-
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
private string inS = "dog cat monkey dog horse dog";
private List<string> rmS = new List<string> {"dog", "cat"};
private string finalString = "";
private string resultString = " ";
private string removeVarious(string iStr, List<string> iListStr)
{
for (int i = 0; i < iListStr.Count; i++)
{
string str = iListStr[i];if (iStr.StartsWith(str)) { iStr = iStr.Remove(0, str.Length + 1); finalString = iStr; } if (iStr.EndsWith(str)) { iStr = iStr.Remove(iStr.Length - str.Length - 1, str.Length + 1); finalString = iStr; } if (iListStr.Count > 0) { iListStr.RemoveAt(0); // recursion here removeVarious(iStr, iListStr); } else { break; } } return resultString.Insert(1, finalString);
}
Note: this was written before Chris changed the accepted output to include the word "cat" at the beginning. Meow. best, Bill
"It is the mark of an educated mind to be able to entertain a thought without accepting it." Aristotle
-
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
my $trimWord = "dog";
my $string = "dog cat monkey dog horse dog";$string =~ s/^($trimWord)+|($trimWord)+$//g;
print $string;
Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
"No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011) -
Shit my eyes are bleeding :)
Software Kinetics Wear a hard hat it's under construction
Metro RSSYou shat your eyes or your eyes are bleeding? :laugh: :-D :thumbsup:
Just along for the ride. "the meat from that butcher is just the dogs danglies, absolutely amazing cuts of beef." - DaveAuld (2011)
"No, that is just the earthly manifestation of the Great God Retardon." - Nagy Vilmos (2011) "It is the celestial scrotum of good luck!" - Nagy Vilmos (2011) -
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
The function:
-- function
require("lpeg")
d = lpeg.P"dog" + lpeg.P"cat"
g = d^0 * lpeg.C((1-d)^1 * (d^0 * (1-d))^0) * d^0
function trm(s) return lpeg.match(g, s) or "" endthe test:
-- test
t = {
"dog cat monkey dog horse dog",
"dogcatmonkeycatcatcat",
"dog",
"doghorsedogdog dog",
"monkey",
"catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat"
}for i,v in ipairs(t) do
print ("'" .. v .. "'" .. " -> " .. "'" .. trm(v) .. "'")
endthe output:
'dog cat monkey dog horse dog' -> ' cat monkey dog horse '
'dogcatmonkeycatcatcat' -> 'monkey'
'dog' -> ''
'doghorsedogdog dog' -> 'horsedogdog '
'monkey' -> 'monkey'
'catcatdogcathorse sheep dog cat pig horse sheepcatmonkeydogcat' -> 'horse sheep dog cat pig horse sheepcatmonkey'If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke
[My articles]