Coding Challenge
-
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
Chris Maunder wrote:
Given a string of text, trim from each end of the text each all occurrences of a given set of strings
Assuming (from your sample) you only want to remove a single item from each end (hence the leading 'cat' remains), then the below would seem to provide the requisite output and I feel earn bonus points for its simplicity, elegance and the fact that it's the first opportunity I've had to do c# for nearly a year!
private string CodingChallenge(string source, string[] removals)
{
string delimiter = " ";
bool leftDone = false;
bool rightDone = false;foreach (string s in removals) { if (!leftDone && source.Substring(0, s.Length) == s && source.Substring(s.Length, 1) == delimiter) { source = source.Substring(s.Length); leftDone = true; } if (!rightDone && source.Substring(source.Length - s.Length) == s && source.Substring(source.Length - s.Length - 1, 1) == delimiter) { source = source.Substring(0, source.Length - s.Length); rightDone = true; } } return source; }
MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')
-
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
Need to check this with other strings, debug some more, improve comments and string handling in main(), etc. But still....here it goes:
#include "stdafx.h"
const wchar_t whitechar = ' ';
const bool IncludeWhiteSpace = true;
const wchar_t* wordstoremove[] = {L"dog", L"cat"};const wchar_t* strtoparse = L"dog cat monkey dog horse dog"; //Len 28
int ltoparse;
const int numwords = 2;int wordlen[numwords];
//Positions in the original string to rip
int pos_orig_from;
int pos_orig_to;//Len of left and right copies
int left_len;
int right_len;//Gets hoy many bytes per char
void ProcessLeft(wchar_t* strresult)
{
bool bContinue = true;pos\_orig\_from = left\_len = 0; while (bContinue) { //Check for whitespaces. If there are, copy them if (strtoparse\[pos\_orig\_from\] == whitechar) { pos\_orig\_from ++; if (IncludeWhiteSpace) { strresult\[left\_len\] = whitechar; left\_len ++; } } else { bContinue = false; for (int i = 0; i < numwords; i++) { //Compare strings wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_from; if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0) { pos\_orig\_from += wordlen\[i\]; bContinue = true; break; } } } }
}
void ProcessRight(wchar_t* strresult)
{
bool bContinue = true;pos\_orig\_to = right\_len = ltoparse - 1; while (bContinue) { //Check for whitespaces. If there are, copy them if (strtoparse\[pos\_orig\_to\] == whitechar && IncludeWhiteSpace) { pos\_orig\_to -= 1; if (IncludeWhiteSpace) { strresult\[right\_len\] = whitechar; right\_len -= 1; } } else { bContinue = false; for (int i = 0; i < numwords; i++) { //Compare strings //To check right, start from end and substract string to compare len wchar\_t\* strcompare = (wchar\_t\*)strtoparse + pos\_orig\_to - wordlen\[i\] + 1; if (wcsncmp(strcompare, wordstoremove\[i\], wordlen\[i\]) == 0) { pos\_orig\_to -= wordlen\[i\]; bContinue = true; break; } } } }
}
int _tmain(int argc, _TCHAR* argv[])
{//Load len of words to avoid rechecking for (int i=0; i
-
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 preservesYour former client base is showing mate - calling a method Stripper.
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
-
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 was fed up, so here it is in c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace CodeChallenge
{
class Program
{
private static List<string> wordsToRemove = new List<string>() { "dog", "cat" };static void Main(string\[\] args) { string text = "dog cat monkey dog horse dog"; string\[\] words = text.Split(' '); string\[\] output; int start = 0; int end = 0; // test the start if (wordsToRemove.Contains(words\[0\]) && words.Length > 0) start = 1; // test the end if (wordsToRemove.Contains(words\[words.Length - 1\]) && words.Length != start) end = (words.Length - 1) - start; else end = words.Length - start; //build output = new string\[end\]; Array.Copy(words, start, output, 0, end); //output Console.WriteLine(string.Join(" ",output)); }
}
} -
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
Probably not the most efficient, but in C#, this works:
using System.Text.RegularExpressions;
var source = "dog cat dog horses monkeys dog";
var stringsToTrim = new[] { "dog", "cat" };
var trimmedString = Regex.Replace(source, string.Format("^({0})|({0})$", string.Join("|", stringsToTrim )), "");
Console.WriteLine(trimmedString);Live demo: http://rextester.com/GTLWO64640[^] Making above shorter:
using System.Text.RegularExpressions;
Console.WriteLine(Regex.Replace("dog cat dog horses monkeys dog", string.Format("^({0})|({0})$", string.Join("|", "dog", "cat")), ""));
-
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
-
Quote:
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
Chris Maunder wrote:
result = Regex.Replace
That's sweet. And amazingly simple. Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
Your former client base is showing mate - calling a method Stripper.
Forgive your enemies - it messes with their heads
"Mind bleach! Send me mind bleach!" - Nagy Vilmos
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
Pete O'Hanlon wrote:
Your former client base is showing mate - calling a method Stripper.
I am scarred for life! ;P Marc
My Blog
An Agile walk on the wild side with Relationship Oriented Programming -
Quantum collapse occurs due to quantum interactions with something else ("observation"). There is no need for that interaction to be conscious or human, it just means that one quantum system is disturbed through interaction with something else - such as a cat. :)
What the hell is the matter with you guys...? :sigh:
-
Won't work if you have "dog dog text". It will only remove the first "dog"
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP
5th Jan: But you said there was nothing in the spec about whitespace, so only removing the first dog is permissible. FWIW: Here is my solution in JavaScript (not the fastest, but still quite short a) Only removing the first dog (if there are multiple dogs)
alert(/^(dog|cat)*(.*?)(dog|cat)*$/.exec("dog cat monkey dog horse dog")[2])
b) Allowing removal of packs of dogs and cats optionally separated by whitespace chars:
alert(/^(\s*(dog|cat))*(.*?)((dog|cat)\s*)*$/.exec("dog cat monkey dog horse dog")[3])
6th Jan: Modified Clarifications in other responses suggest that whitespace is to be preserved and is not significant when looking for leading / trailing texts and that a general solution is required rather than looking only for dogs and cats bracketing "dog cat monkey dog horse dog". So, today's JavaScript version is ...
function strim(str, texts)
{
return str.replace(
new RegExp(
'^((\\s*)(' + // $2 = leading whitespace
texts.join('|') +
'))*(.*?)((' + // $4 = middle portion
texts.join('|') +
')(\\s*)?)*$', // $7 = trailing whitespace
'ig'
),
'$2$4$7'
);
}alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]));
alert(strim('dog dog text', [ 'dog', 'cat' ]));To see the spaces, change the alerts to
alert(strim('dog cat monkey dog horse dog', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~monkey~dog~horse~
alert(strim('dog dog text', [ 'dog', 'cat' ]).replace(/ /g, '~')); // ~~textNote: This will not work if the texts for testing at the start and end include any special RegExp chars, e.g.
. * + ? {or}
. -
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
Hi, I have gotten the CodeProject newsletters for several years and used the site, but this it the first time I have posted, but this topic was so fun I just had to! :) I found the task was not clear on one topic, namely which resulting string should be the answer if several are possible? It can happen if the matches at the beginning and end overlap, if my assumption that the patterns you remove can not overlap is correct? Anyway, I solved it with the assumption that what is wanted is the shortest possible resulting string, why else would you trim a string :laugh:
#include <cstdio>
#include <vector>#include "ahocorasick.h"
using namespace std;
using namespace ac;// arbitraty length limits
#define MAX_TEXT 1000000
#define MAX_PATTERN 1000000struct interval {
int begin,end;interval(int b, int e) : begin(b), end(e) { } // reverse the interval given the total length is n interval reverse(int n) const { return interval(n - end, n - begin); }
};
interval trim(int len, vector<interval> & intervals);
int main() {
char * patternbuf;
char ** patterns;
char text[MAX_TEXT];
int npatterns;scanf("%d", &npatterns); getchar(); patterns = new char\*\[npatterns\]; patternbuf = new char\[npatterns \* MAX\_PATTERN\]; for (int i = 0; i < npatterns; ++i) { patterns\[i\] = &patternbuf\[i\*MAX\_PATTERN\]; gets(patterns\[i\]); // is dangerous and should not be used! } gets(text); // match the patterns to find all the possible places to trim the string aho\_corasick matcher(npatterns, patterns); vector<int> \* matches = matcher.get\_matches(text); // build a list of intervals of the matches vector<interval> intervals; for (int i = 0; i < npatterns; ++i) { int len = matcher.get\_pattern\_size(i); for (vector<int>::iterator it = matches\[i\].begin(); it != matches\[i\].end(); ++it) intervals.push\_back(interval(\*it, \*it+len)); } // trim the string as much as possible, i.e. find the shortest interval of // the original string that can result from trimming interval result = trim(strlen(text), intervals); // print the result text\[result.end\] = '\\0'; printf("\\"%s\\"\\n", &text\[result.begin\]); // clean up delete \[\] patternbuf; delete \[\] patterns; return 0;
}
-
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
where i can send my solution?? :P
-
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'm sorry but this is not a challenge. If you want a real challenge go to ProjectEuler.com. There you will find over 350 easy to difficult challenges. I have learned a ton from the site and have only completed 45 problems so far. Wish I had more time to work the problems. Regards
-
I'm sorry but this is not a challenge. If you want a real challenge go to ProjectEuler.com. There you will find over 350 easy to difficult challenges. I have learned a ton from the site and have only completed 45 problems so far. Wish I had more time to work the problems. Regards
I'm sorry but I think you missed the point of this entire thread. Alternatively you could post your own challenge. I'd love to see everyone else throwing their challenges into the ring.
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
Hmm, i read here since more than one, year but never posted something, but this sounds not to difficult. euphoria 4.0.x include std/text.e include std/console.e puts(1,trim("dog cat monkey dog horse dog","dogcat",0)&"\n") any_key() this should produce your final output Andreas
-
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
OK, this is simpler than what I was concocting yesterday and it's not fully tested, but it works with your sample strings. I started by writing a simple Spell Check Tree class (in C# it's much simpler than it was with C back in college):
namespace PIEBALD.Types
{
public sealed class SpellCheckTree
{
public enum SearchState
{
NotFound = -1
,
Inconclusive = 0
,
Found = 1
}private sealed class TreeNode : System.Collections.Generic.Dictionary<char,TreeNode> {} private readonly TreeNode tree ; private TreeNode current ; public SpellCheckTree ( ) { this.current = this.tree = new TreeNode() ; return ; } public void Reset ( ) { this.current = this.tree ; return ; } public void Add ( System.Collections.Generic.IEnumerable<char> String ) { TreeNode temp = this.tree ; foreach ( char c in String ) { if ( !temp.ContainsKey ( c ) ) { temp \[ c \] = new TreeNode() ; } temp = temp \[ c \] ; } temp \[ System.Char.MaxValue \] = new TreeNode() ; return ; } public SearchState Find ( char C ) { SearchState result = SearchState.Inconclusive ; if ( !this.current.ContainsKey ( C ) ) { result = SearchState.NotFound ; } else { this.current = this.current \[ C \] ; if ( this.current.ContainsKey ( System.Char.MaxValue ) ) { result = SearchState.Found ; } } return ( result ) ; }
}
}Then I wrote a Trim method to use it:
namespace PIEBALD.Lib
{
using System.Linq ; /* Laziness/expedience */public enum TrimFrom
{
Left = 1
,
Right = 2
,
Both = 3
}namespace LibExt.Trim
{
public static partial class LibExt
{
public static string
Trim
(
this string Subject
,
TrimFrom TrimFrom
,
params string[] Strings
)
{
System.Text.StringBuilder result = new System.Text.StringBuilder ( Subject ) ;
in -
An 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
I read it as, "if you want to trim whitespace, then supply them as a 'string to be removed'".
-
It thought it was both alive and dead until you had a look in the box at which point it became alive or dead. A bit late but still; Erwin Schrödinger has sent us a Christmas present. The kids are going to be delighted or distraught on Christmas Day.
Every man can tell how many goats or sheep he possesses, but not how many friends.
-
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
Chris Maunder... without having to think too much (and thus stress my feeble brain)
include 'win32a.inc'
format PE console 4.0
entry start
;*********************************************
section '.data' data readable writeable_s db '%s',13,0
i_string db 'dog cat monkey dog horse dog'
o_string db 21 dup(0);*********************************************
section '.text' code readable executable
;*********************************************
start: ;fasm_dogcat.fasmmov ebx,3
xor ecx,ecx
above:
mov eax,dword[i_string+ebx+ecx*4]
mov dword[o_string+ecx*4],eax
inc ecx
cmp ecx,5
jnz above
mov ax,word[i_string+ebx+ecx*4]
mov word[o_string+ecx*4],axcinvoke printf,_s,o_string
; >"C:\_sys\temp\shell.exe"
;$20,'cat monkey dog horse',$20,0
; >Exit code: 0
;*********************************************
invoke ExitProcess,0
;***********************************************
section '.idata' data import readable writeable
library kernel32,'kernel32.dll',\
user32,'user32.dll',\
msvcrt,'msvcrt.dll'
include 'api\kernel32.inc'
include 'api\user32.inc'
import msvcrt,\
printf,'printf'
;***********************************************brianO
-
Chris Maunder... without having to think too much (and thus stress my feeble brain)
include 'win32a.inc'
format PE console 4.0
entry start
;*********************************************
section '.data' data readable writeable_s db '%s',13,0
i_string db 'dog cat monkey dog horse dog'
o_string db 21 dup(0);*********************************************
section '.text' code readable executable
;*********************************************
start: ;fasm_dogcat.fasmmov ebx,3
xor ecx,ecx
above:
mov eax,dword[i_string+ebx+ecx*4]
mov dword[o_string+ecx*4],eax
inc ecx
cmp ecx,5
jnz above
mov ax,word[i_string+ebx+ecx*4]
mov word[o_string+ecx*4],axcinvoke printf,_s,o_string
; >"C:\_sys\temp\shell.exe"
;$20,'cat monkey dog horse',$20,0
; >Exit code: 0
;*********************************************
invoke ExitProcess,0
;***********************************************
section '.idata' data import readable writeable
library kernel32,'kernel32.dll',\
user32,'user32.dll',\
msvcrt,'msvcrt.dll'
include 'api\kernel32.inc'
include 'api\user32.inc'
import msvcrt,\
printf,'printf'
;***********************************************brianO
You get serious Man Points for that. :beer:
cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP