View Full Version : Code Challenge!
beetle
01-02-2003, 08:40 PM
Hey everyone
I've had this thought in my mind for a while. I think it would be fun to have a code challenge, say somebody (like myself) presents a problem and codingforums visitors (that's you people) can take a crack at presenting the shortest and/or most efficient algorithm. The 'Winner' would only get bragging rights or whatever. Sorry, no toaster ovens or Hawaiian vacations :D
I'll kick off this idea with a challenge of my own, something relatively simple.
The Challenge
Create a function (named convert) to reverse the text inside a text input, and populate that input with the reversed text.
General Rules & Regs No non-ECMA script functions or methods (i.e. no proprietary JScript stuff)
Functions and methods from any ECMA script version are OK
One line of code is defined as: amount of code that can be used withour requiring a semicolon for separation, excluding semicolons used by for loops and the like.
Lines of code not counted are: Function declarations, any line consisting solely of a bracket (The example belowis 5 lines)
If two contestants have entries with the same number of lines, then characters in that line will be counted (not including spaces) to determine a winner.
Shortcuts/shorthand such as ternary statments and literal notation, etc are OK.Rules specific to this challenge Function convert must receive one and only one parameter, a reference to the input.
Post only your function, and not the whole HTML page. I will assume you have used my example as a shell
Contest will close at 12:00 pm CST on Jan 03, 2003Grading 4 lines or more: Are you really trying?
3 lines: Not bad!
2 lines: Very good!
1 line: Excellent!Example<html>
<head>
<title>Contest</title>
<script type="text/javascript">
function convert( inputObject )
{
var stringIn = inputObject.value;
var stringOut = "";
for ( var i = stringIn.length; i >= 0; i-- )
{
stringOut += stringIn.charAt(i);
}
inputObject.value = stringOut;
}
</script>
</head>
<body>
<form>
<input type="text" name="text1" size="80" />
<br />
<input type="button" value="convert" onclick="convert( this.form.text1 );" />
</form>
</body>
</html>Note: This is solvable with one line, I've done it already ;)
mordred
01-02-2003, 08:58 PM
function convert(t) {
t = t.value.split('').reverse().join('');
}
So now I look that up in the ECMA Specs....
EDIT: Seems ok, if I can rely on the method descriptions in Flanagans Definitive Guide.
beetle
01-02-2003, 09:03 PM
Nice mordred :thumbsup:
Extra kudos to the person who can do this WITHOUT the reverse() method ;)
Aside: Anyone else think this could be fun? Or has my cheese fallen from my cracker? :p
scroots
01-02-2003, 09:59 PM
2 lines - i think, as there are only 2 semi colons
<script type="text/javascript">
function convert( inputObject ){
var x=""
{
for ( var i = inputObject.value.length; i >= 0; i-- )
{
x += inputObject.value.charAt(i)
}
inputObject.value = x
}
}
</script>
any good?
scroots
beetle
01-02-2003, 10:09 PM
Sorry scroots, perhaps I should have been more clear. I recognize that end-of-line semicolons aren't required in javascript, but if I were to compress your code onto one line, it would not work. So, I count your code as four linesfunction convert( inputObject ){
var x="" //1
{
for ( var i = inputObject.value.length; i >= 0; i-- ) //2
{
x += inputObject.value.charAt(i) //3
}
inputObject.value = x //4
}
}
scroots
01-02-2003, 10:13 PM
right ok, i thought about that after posting.
time for a rethink and i`m gona do it without using the reverse method
scroots
Tanker
01-02-2003, 10:27 PM
I was bored, heres what I came up with , without reverse();
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Reverse It</title>
<script language="JavaScript1.2">
<!--
function reverseText(oldText){
document.myForm.myText.value = "";
for(i=oldText.length;i>=0;i--)document.myForm.myText.value += oldText.charAt(i);
}
//-->
</script>
</head>
<body>
<form name="myForm">
<input type="text" name="myText">
<input type="button" value="GO" onClick="reverseText(document.myForm.myText.value)">
</form>
</body>
</html>
beetle
01-02-2003, 10:44 PM
Thanks Tanker, a nice entry. Your code is deserving of a Very good! rating, but you didn't read the rules very closely, so I'll have to give you a Not bad! instead ;)
Heh, I feel like the Soup Nazi :D
whammy
01-03-2003, 12:20 AM
Hmm, I tried to do it without looking at your example (which turned out to be pretty easy) - but I also tried quite a few different ideas to shorten the script, and came up with basically the same thing as everyone else did, in 3 lines (if I read the rules right):
function convert(str) {
var newstr = "";
for (var i = str.length; i >= 0; i--) newstr += str.charAt(i);
return newstr;
}
I really like mordred's example... I'm waiting to see your method of doing it without reverse() in one line (or whether he bested you ;))! I had some ideas on how to do it in 1 or 2 lines, by perhaps eliminating the first character from the string while adding it to the end, but I couldn't get the syntax right, or I was missing some crucial key. :(
P.S. I think the name of a function should describe as precisely what it does as it can, IMHO... convert is a bad choice in this case, since it doesn't say anything about the "function" of the function. I'd upgrade your assessment of Tanker's "grade" just because he named the function "reverseText" (in camel casing, no less, as all built-in javascript functions use!). That definitely would garner kudos from me, if I was working on an application he wrote! ;)
Borgtex
01-03-2003, 01:01 AM
very ugly, but one line; semicolon doesn't count because is part of a string, that has to be evalued ;)
function rvtxt(s) {
return eval('ns=""; for (var i = s.length; i >= 0; i--) ns += s.charAt(i)')
}
whammy
01-03-2003, 01:04 AM
Ew, using eval() kind of stinks (yeah, it is ugly hehe), but it is one line... since beetle didn't specify NOT using reverse, I think mordred is the winner so far... since his code should run faster by a nanosecond or so... ;)
But that's good! (And I'm not judging this, I'm waiting to see what beetle came up with, since obviously if I wanted soup, he would kick me out the door! ;)).
The cool thing about this kind of challenge is it's amazing how many different types of approaches will work for the same "problem". ;) This should really be a class assignment...
ca_redwards
01-03-2003, 01:33 AM
function convert(t) { return (t.length?convert(t.slice(1))+t.charAt(0):t) }
Don't you just love recursion?
This reminds me of how much I struggled to make my HTML() bookmarklet library (http://www.angelfire.com/ca/redwards/html__.calendar.html) "template" functions just one line!
beetle
01-03-2003, 01:33 AM
Yes Whammy, exactly! I love seeing all the different ways. Of course, in light of some responses I probably would have made the rules stricter (no eval() ;)) but I did not, so this is all valid. I also might have preferred to restrict the coder to only String methods (which my solution satisfies). I don't mind being bested, however, I will admit that.
However, Borgtex's and Whammy's solutions cheat a bit because some of the javascript code is unseen and executed in the event, which I did not intend (i.e. there should NOT be a return statement). I did state the the FUNCTION should populate the input. Any submissions with a return will not be graded.
Besides, this was just a starter, something to get this idea going, and help us figure out what can happen (like people using eval ;) )
Oh, and whammy, about the function name, I agree. However, this excercise is not about proper conventions or anything like that, but about making you think beyond what you normally do. In this case, the code INside the function is what it important. I stand by my decision :D
whammy
01-03-2003, 01:35 AM
Yikes, I think ca_redwards might have bested us all? ;)
Haven't tested it yet though... going to do so right now. :D
P.S. Damn! He did it... and actually that was what I was TRYING to do. I think I need to take some lessons from this guy (I've never claimed to be a javascript GURU anyway!). :)
whammy
01-03-2003, 01:40 AM
P.S. beetle, I dunno about your stance on not passing certain "unseen" parameters to a function... ;)
If that's gonna be a rule, declare it next time. :D
P.S. So you're saying mordred gotcha, huh? I gotta see your solution as opposed to red's... that's over my head for the moment. ;)
beetle
01-03-2003, 01:45 AM
Forgive my blockheadedness, whammy, unseen parameters? The only two that I can think of are event in Gecko and arguments, which is really more of a property of the function. Nobody's examples use either of those.
Did mordred beat me? Doesn't matter, this isn't about you guys competing against me, it's about you competing agaisnt eachother. :D
Don't worry, I'll post my solution at the end ;)
whammy
01-03-2003, 01:46 AM
have you tried ca_redwards version?!? If yours is better, please let me know! lol
P.S. Don't worry, I KNOW I'm no guru at this stuff - and it's not a competition... I usually just code something quick that works, who cares if it's one line or 5...
But I like to learn the BEST way, that's why I hang around to learn from you guys... and it just got me a 20.637xxxx percent raise at my job, btw!!! Have you ever heard of a 20% raise?!? I haven't... :D YAY! That gives me a bit more money (not going to specify that), before taxes every couple of weeks... :D :D :D
P.S.:
I also might have preferred to restrict the coder to only String methods (which my solution satisfies).
I guess what I meant by "unseen parameters" was assuming that you were passing a string to the function, but right now I don't know what I was thinking at that point, because I'm too busy learning, lol...
Borgtex
01-03-2003, 01:55 AM
ca_redwars and mordred answers prove that the Challenge was a great idea, as they surprised me and learned new things.
Thanks beetle :D
whammy
01-03-2003, 01:56 AM
I'll DEFINITELY agree with that statement! :)
P.S. beetle, you said a function shouldn't return a value - in that case aren't you limiting the function to modifying form input, instead of the plethora of things it could return otherwise?..
I thought that was the basic "function" of a function? To return a value, boolean or otherwise?.. :confused: I guess we're getting into semantics here...
ca_redwards
01-03-2003, 02:00 AM
The .slice() function is defined on both Array and String. I used the String one. I could have used .substr() or even .substring(), but those are more characters!
Originally posted by whammy
have you tried ca_redwards version?!? If yours is better, please let me know! lol
P.S. Don't worry, I KNOW I'm no guru at this stuff - and it's not a competition... I usually just code something quick that works, who cares if it's one line or 5...
But I like to learn the BEST way, that's why I hang around to learn from you guys... and it just got me a 20.637xxxx percent raise at my job, btw!!! Have you ever heard of a 20% raise?!? I haven't... :D YAY! That gives me a bit more money (not going to specify that), before taxes every couple of weeks... :D :D :D
P.S.:
I also might have preferred to restrict the coder to only String methods (which my solution satisfies).
I guess what I meant by "unseen parameters" was assuming that you were passing a string to the function, but right now I don't know what I was thinking at that point, because I'm too busy learning, lol...
whammy
01-03-2003, 02:07 AM
Thanks for your recursion example, ca_redwards... now can you explain the logic in detail to all the newbies (including me ;)) who frequent the forum? :D
Actually I think I get it for the most part... but explanations are always a good thing. :D
ca_redwards
01-03-2003, 02:22 AM
In my first message, I offered the solution...
function convert(t) { return (t.length?convert(t.slice(1))+t.charAt(0):t) }
1st, I should explain my use of the conditional expression ternary operator. This ternary operator takes three operands--- a condition to be evaluated, and two possible result values.
condition ? valueT : valueF
2nd, I should explain my use of t.length as a boolean as the condition operand. Any object can be treated as a boolean, with zero or empty or null treated as false.
3rd, I might explain my condition false result. I could have returned an empty string, but that would take two characters! The t variable is only one.
4th, I must explain my condition true result. It is actually a concatenation of the result of convert(t.slice(1)) and first character .charAt(0)
3.5th, I should explain my use of convert() in the concatentation. By calling the convert function again, a new instance of the convert function is created with the argument t.slice(1)
3.6th, I reason that t.slice(1) employs all but the first character of t.
Viola!
beetle
01-03-2003, 02:26 AM
Originally posted by ca_redwards
Viola! Viola?
http://math.holycross.edu/~little/viola.jpg
Surely you mean Voila! ;)
glenngv
01-03-2003, 02:29 AM
but isn't the parameter to the convert() function should be the object reference to the input element not its value?
ca_redwards
01-03-2003, 02:29 AM
Did you just happen to have that image lying about?
Some people must have some very organized image collections!
beetle
01-03-2003, 02:30 AM
Originally posted by ca_redwards
Did you just happen to have that image lying about?
Some people must have some very organized image collections! Google, baby.
ca_redwards
01-03-2003, 02:36 AM
You could make the text1 onclick code read...
"this.form.text1.value=convert(this.form.text1)"
Originally posted by glenngv
but isn't the parameter to the convert() function should be the object reference to the input element not its value?
So, yes... I suppose that you're right.
The largest one-liner so far (tis really one line, just made code unreadable by removing line breaks, and you'll find that it is just ternary operators and such):
function convert(input, offset) {
return (input.value.length > 1 && 2*(offset || 0) < input.value.length) ?
((typeof offset == 'undefined') ?
(input.value = (
input.value.charAt(input.value.length - 1) +
reverse(input, 1) +
input.value.charAt(0)
))
:
(
input.value.charAt(input.value.length - 1 - offset) +
reverse(input, offset+1) +
((input.value.length - 1 - offset == offset) ? '' : input.value.charAt(offset))
))
: '';
}
And yes, I pass around an extra variable. So shoot me. However, it *must* initially be called with only the input argument, so there.
mordred posted the only solution I'd actually use, but he found this thread before me. :p
ca_redwards
01-03-2003, 03:01 AM
Okay, Beetle. What's your solution?
beetle
01-03-2003, 03:06 AM
Ok, I've decided to end this challenge early. I think everyone is beginning to get the idea about how this can work and be really cool. I, myself, have learned that if you think you've made strict rules, you haven't ;)
Ok, the awards :D
Coolest Concept
ca_redwards
Most efficient and practical
mordred
Most stupendous waste of code that really IS one line
jkd (poke, poke!) ;)
Challenge Winner
Tanker
Ok, here's why mordred and ca_redwards didn't tie for a win (like they should have ;)) ca_redwards' submission while very impressive didn't follow the rule about the parameter being passed. mordred's example is ALMOST perfect, except that if any of you took the time to test it you would have noticed that it doesn't work (a bug unrelated to the algorithm) Sorry, mordred! I know I didn't specifically mention that submitted code actually had to work, but that should be implied :p Tanker's submission is the only one that successfully achieves the task and does so in an impressive two lines.
Ok, now what everyone else has been waiting for, my solution :D
Coolest solution using regex
function convert( t )
{
for( var i=t.value.length; i>0; t.value = t.value.replace( new RegExp( "(.)(.{"+(i--)+"})(.*)" ), "$2$1$3" ) ) {}
}What can I say, I'm addicted to regex lately :rolleyes:
I hope that beyond the wonderful code knowledge garnered here, you folks out there have also learned what to expect and do when posting your own challenges!
Congrats everyone! Thanks for participating!
P.S. Is this post a record for smilie use or what? :cool:
glenngv
01-03-2003, 03:25 AM
Tanker's solution also didn't follow your rule to use input as the parameter. And I think he did it in 3 lines not 2. :D
beetle
01-03-2003, 03:33 AM
Thanks glenn. apologies everyone, I have picked a poor evening to do this. Seriously, my house is like a zoo tonight. I'm surprised I can type in coherent english.
Don't worry about the winner here, this contest, as I've mentioned several times, is just a starter/beta test. For future reference
When posting a challenge
Be CLEAR and SPECIFIC with your rules
TEST and scrutinize EACH submission THOROUGHLY
When answering a challenge
READ and FOLLOW the rules
TEST your code
mordred
01-03-2003, 11:46 AM
Originally posted by beetle
mordred's example is ALMOST perfect, except that if any of you took the time to test it you would have noticed that it doesn't work (a bug unrelated to the algorithm) Sorry, mordred! I know I didn't specifically mention that submitted code actually had to work, but that should be implied :p
First, I feel of course flattered that my submission was called the most practical and efficient. I like ca_redwards approach much more though, because of it's very clever use of recursion. I struggled a little with a second approach that took the way you did beetle, because I had in mind you were recently fascinated by the use of the RegExp constructor (;)), but since all my tries had more chars than my original submission, I just gave up...
Second: What bug did you found? And how was it unrelated to the algorithm. Granted, I understood the challenge so that the code should actually work, and I did some test runs with sample foobar data in IE5.5, so.... did you test that in Netscape2.0 or what? You only said that the code should exist of ECMAScript compatible syntax. If you want the code to work in browsers, it would be nice to know in which ones... just a thought after the match.
I liked the idea of this code challenge. Looks a bit like Perl golf, but that's not a bad thing. Thanks! :)
Algorithm
01-03-2003, 12:13 PM
Mordred's code:function convert(t) {
t = t.value.split('').reverse().join('');
}Correct code (I think):function convert(t) {
t.value = t.value.split('').reverse().join('');
}See the difference?
mordred
01-03-2003, 02:00 PM
Oh yes indeed! :o
That's the color-blindness concerning one's own code, and so is beetle very correct with his decision.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.