Post your strangest loop and win (up to) 4 free passes to Strange Loop!

105 views
Skip to first unread message

Alex

unread,
Aug 3, 2010, 8:09:00 AM8/3/10
to The Java Posse
The latest Java Posse episode (<a href="http://javaposse.com/
java_posse_317_newscast_for_july_29th_2010">#317</a>) features a short
segment (start around 51:45) of the posse talking about the <a
href="http://strangeloop2010.com">Strange Loop conference</a>. The
Java Posse are giving away four FREE (as in beer) tickets based on a
contest.

The contest is: "Write the strangest loop" (any language is ok). You
should post your answer here and list the number (out of 4) you
possibly could use. The answer will be judged by the posse (and
me!).

I'm not sure what the deadline for the contest will be but we'll post
that here.

Give us your loops!

Alex Miller

Matt Passell

unread,
Aug 3, 2010, 12:51:27 PM8/3/10
to The Java Posse
If I were to win, I'd only need one ticket. I'm not sure if this
counts (it might be more appropriate for the Daily WTF), but I once
saw Java code that looked like the following (I don't remember what
was inside the if blocks):

for (int i = 0; i < 4; i++) {
if (i == 0) {
//some code to handle case 0
} else if (i == 1) {
//some code to handle case 1
} else if (i == 2) {
//some code to handle case 2
} else if (i == 3) {
//some code to handle case 3
} else if (i == 4) {
//some code to handle case 4
}
}

I was going to make fun of whoever had written it and ask why on earth
it had been structured as a loop, but I lost my nerve when the version
control system revealed that it had been written by the head of the
engineering team for the small startup I was at. I think I'd be more
courageous about calling him on it at this point. :)

--Matt

Alex

unread,
Aug 3, 2010, 1:23:00 PM8/3/10
to The Java Posse
The deadline for the contest will be Aug. 31st! Give us your loops!

Alex

Vince O'Sullivan

unread,
Aug 3, 2010, 8:09:51 PM8/3/10
to The Java Posse
for (Strange loop : loops)
if (loop.isStrange())
continue;

Kevin Wright

unread,
Aug 3, 2010, 8:25:02 PM8/3/10
to java...@googlegroups.com
For wacky loop madness, it doesn't get much stranger than loop unrolling in C/C++
So I present to you... <drum roll> ...Duff's Device!
(lifted direct from Wikipedia)

send(to, from, count)
register short *to, *from;
register count;
{
	register n=(count+7)/8;
	switch(count%8){
	case 0:	do{	*to = *from++;
	case 7:		*to = *from++;
	case 6:		*to = *from++;
	case 5:		*to = *from++;
	case 4:		*to = *from++;
	case 3:		*to = *from++;
	case 2:		*to = *from++;
	case 1:		*to = *from++;
		}while(--n>0);
	}
}

Such elegance!
Such conciseness!

Why oh why did I ever allow Scala, with it's complexity and ugly, ugly functional constructs to enter my life?
It's nothing but a virtuous life of clean, simple, comprehensible imperative code for me from now on!


--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.




--
Kevin Wright

mail/google talk: kev.lee...@gmail.com
wave: kev.lee...@googlewave.com
skype: kev.lee.wright
twitter: @thecoda

Joseph Darcy

unread,
Aug 3, 2010, 9:11:46 PM8/3/10
to java...@googlegroups.com
On Tue, Aug 3, 2010 at 5:09 AM, Alex <alexd...@yahoo.com> wrote:
> The latest Java Posse episode (<a href="http://javaposse.com/
> java_posse_317_newscast_for_july_29th_2010">#317</a>) features a short
> segment (start around 51:45) of the posse talking about the <a
> href="http://strangeloop2010.com">Strange Loop conference</a>.  The
> Java Posse are giving away four FREE (as in beer) tickets based on a
> contest.
>
> The contest is:  "Write the strangest loop" (any language is ok).  You
> should post your answer here and list the number (out of 4) you
> possibly could use.  The answer will be judged by the posse (and
> me!).

From many years ago when I was first getting into Java, I recall this
infinite Java loop pointed out by the Sumatra project
(http://www.cs.arizona.edu/projects/sumatra/hallofshame/):

while (true) {
try {
return;
} finally {
continue;
}
}

-Joe
(2 passes)

Mark Derricutt

unread,
Aug 3, 2010, 9:23:15 PM8/3/10
to java...@googlegroups.com
Does this even compile?

As you have the do {} inside the first case statement, and all other case's are inside the do.     Since there's not in scope of the case I'd expect this to fail?   But then - I'm no C/C++ guy so who knows what wacky hackery they get up to :)

--
Pull me down under...

Mac

unread,
Aug 3, 2010, 11:41:11 PM8/3/10
to The Java Posse
here is my entry


(defn pure-loop [n]
(println "pure " n)
(if (= n 0)
0
#(danger-loop (dec n))))

(defn danger-loop [n]
(println "danger " n)
(if (= n 0)
0
#(pure-loop (dec n))))



user=> (trampoline pure-loop 20)
pure 20
danger 19
pure 18
danger 17
pure 16
danger 15
pure 14
danger 13
pure 12
danger 11
pure 10
danger 9
pure 8
danger 7
pure 6
danger 5
pure 4
danger 3
pure 2
danger 1
pure 0


It's strange because, well, to use trampoline to do a decreasing loop
is very strange indeed.

Kirk

unread,
Aug 4, 2010, 12:43:51 AM8/4/10
to java...@googlegroups.com
I'll be speaking there so I don't need a pass but thought it might be fun to put in a puzzler.

public class StrangeLoop {
public static void main(String[] args) {
http://www.thestrangeloop.com
do {
System.out.println("Strange Loop");
continue http;
} while (false);
}
}

Puzzler, infinite loop or normal termination?

Regards,
Kirk

Mark Derricutt

unread,
Aug 4, 2010, 12:53:37 AM8/4/10
to java...@googlegroups.com
Or a stack blowout?

Just having a discussion in the office about whether or not the continue will leave a nested stack of do's in the stack..

--
Pull me down under...



Kevin Wright

unread,
Aug 4, 2010, 5:01:18 AM8/4/10
to java...@googlegroups.com
my thinking:

`http:` is the label (followed by a comment that the pre-processor strips out)
`do { ... } while (...)` is the labelled statement
`continue <label>` attempts to transfer control back to the "continue target".  In this case, the labelled do/while loop

a `do {statement} while (expression)` loops will check its expression only once the statement has executed normally (which it hasn't here)
So... the loop will begin again, and continue infinitely, or until an exception is thrown or the JVM is terminated.

No stack involved, at the level of compiled machine code it'll be jump instructions all the way down...


The language spec covering all this is here: http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

For anyone still labouring under the delusion that Java is a simple language, it's a heavyweight document; running to 650 pages in almost 8MB
but you only really need chapter 14 for this question :)


--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.

Steven Siebert

unread,
Aug 4, 2010, 8:55:50 AM8/4/10
to java...@googlegroups.com
I tried to go for a strange "Strange loop" (http://en.wikipedia.org/wiki/Strange_loop)...but I ended up with a recursive loop of doom.  Please forgive the quick thrown-together implementation =)

(2 passes, please =)

Given a "normal" string, this app would loop through and resolve the acronym with the full break out and put the acronym in parenthesis after it.  Given recursive acronyms, all hell breaks loose.


import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Lets make that String understandable to management....
 */
public class Main {


    public static void main(String[] args) {

        //replace var test with cli/arg input
        String test = "In addition to java you can write plugins for the "
                + "GNU tool Nagios using PHP";
        while (AcronymFinder.hasAcronym(test)) {
            test = AcronymFinder.explodeAcronym(test);
            System.out.println(test);
        }
    }

    private static class AcronymFinder {

        private static Pattern p = Pattern.compile("([a-zA-Z]*)[\\s|\\.]");
        /**
         * Takes in a String and checks it against the acronym dictionary,
         * resolving any acronyms in the process
         *
         * @param raw
         * @return
         */
        public static String explodeAcronym(String raw) {
            String out = null;

           
            Matcher m = p.matcher(raw);

            StringBuilder sb = new StringBuilder();

            while (m.find()) {
                try {
                    Acronyms a = Acronyms.valueOf(m.group(1));
                    sb.append(a.resolve());
                    sb.append(" (" + m.group(1) + ")"); //the parens prevents the acronym from getting picked up twice, due to regex impl
                } catch (IllegalArgumentException e) {
                    sb.append(m.group(1));
                }
                sb.append(" ");
            }
            if (sb.length() > 0) {
                out = sb.toString();
            } else {
                out = raw;
            }
            return out;
        }

        public static boolean hasAcronym(String raw) {
            Matcher m = p.matcher(raw);

            while (m.find()) {
                try {
                    Acronyms a = Acronyms.valueOf(m.group(1));
                    return true;
                } catch (IllegalArgumentException e) {
                }
            }
            return false;
        }
    }

    private enum Acronyms {

        GNU("GNU is Not Unix"),
        Nagios("Nagios Ain't Gonna Insist On Sainthood"),
        PHP("PHP Hypertext Preprocessor");
        private String full;

        private Acronyms(String f) {
            full = f;
        }

        public String resolve() {
            return full;

Fabrizio Giudici

unread,
Aug 4, 2010, 9:06:31 AM8/4/10
to java...@googlegroups.com, Kevin Wright

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 8/4/10 11:01 , Kevin Wright wrote:
>
> For anyone still labouring under the delusion that Java is a
> simple language, it's a heavyweight document; running to 650 pages
> in almost 8MB but you only really need chapter 14 for this question
> :)
>

Absolute figures are mostly worthless... comparisons help. How long
are the specs of Scala? Of course, I presume it might also depend on
the writing style.

- --
Fabrizio Giudici - Java Architect, Project Manager
Tidalwave s.a.s. - "We make Java work. Everywhere."
java.net/blog/fabriziogiudici - www.tidalwave.it/people
Fabrizio...@tidalwave.it
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkxZZdYACgkQeDweFqgUGxcviQCbBSreTUXxWeVBlLjqqLfJSSWM
VY0AnjlJLJZt25fUTVnGVZIAyB+AsTAx
=j+FW
-----END PGP SIGNATURE-----

Reinier Zwitserloot

unread,
Aug 4, 2010, 10:25:21 AM8/4/10
to The Java Posse
Yes, Mark, it does. C works in mysterious ways, and this is just one
in a long, possibly endless, procession of them. Duff's device is one
of those hallowed "WTF? Oh.. Ooooh! I get it! Whoever cooked this up
is an evil genius!!!" optimizations useful in the early days of
computing. The wikipedia page has a lengthy treatment on the topic,
but the basic mechanics behind why this is legal in C is this:

1. A switch statement's body is simply like any other block, with as
any extra that you can shove any number of case statements in it.
2. switch works by jumping to the right case statement.
3. In C, you may jump right into the middle of a loop, without
breaking things.

Most folks would say that in java you can only jump out of LOOPS,
which explains why it doesn't work, but this isn't true. It doesn't
work in java because, switch blocks are defined as containing a 0-n
set of (case/default statement followed by 0-n statements), whereas in
C its defined as containing 0-n statements, and case/default are also
statements. You CAN in fact jump around indiscriminately in java code
and it works just fine. Behold this code:

foo: {
System.out.print("Hello, ");
if (0 < System.currentTimeMillis()) break foo;
System.out.println("World!");
System.exit(0);
}

System.out.println("Universe!");

which will print "Hello, Universe!" if your system clock is set later
than Jan 1st, 1970, and causes no compilation problems at all. This
indiscriminate breaking out of any code block, not just those
representing loops, is in fact a holdover from C, where 'break' in a
switch statement, which was after all defined just as a glorified goto
form, required this. In java this isn't necessary (switch being
differently defined), but nevertheless you can break out of whatever
you want, loop or no.

Which, I guess, is my entry for 'strange loop': It's so strange, one
could argue it's not a loop at all!

NB: I don't need a ticket, I can't make the date, but I couldn't
resist :P


On Aug 4, 3:23 am, Mark Derricutt <m...@talios.com> wrote:
> Does this even compile?
>
> As you have the do {} inside the first case statement, and all other case's
> are inside the do.     Since there's not in scope of the case I'd expect
> this to fail?   But then - I'm no C/C++ guy so who knows what wacky hackery
> they get up to :)
>
> --
> Pull me down under...
>
> On Wed, Aug 4, 2010 at 12:25 PM, Kevin Wright <kev.lee.wri...@gmail.com>wrote:
>
>
>
> > For wacky loop madness, it doesn't get much stranger than loop unrolling in
> > C/C++
> > So I present to you... <drum roll> ...Duff's Device!
> > (lifted direct from Wikipedia)
>
> > send(to, from, count)register short *to, *from;register count;{
> >    register n=(count+7)/8;
> >    switch(count%8){
> >    case 0: do{     *to = *from++;
> >    case 7:         *to = *from++;
> >    case 6:         *to = *from++;
> >    case 5:         *to = *from++;
> >    case 4:         *to = *from++;
> >    case 3:         *to = *from++;
> >    case 2:         *to = *from++;
> >    case 1:         *to = *from++;
> >            }while(--n>0);
> >    }}
>
> > Such elegance!
> > Such conciseness!
>
> > Why oh why did I ever allow Scala, with it's complexity and ugly, ugly
> > functional constructs to enter my life?
> > It's nothing but a virtuous life of clean, simple,
> > comprehensible imperative code for me from now on!
>
> > On 4 August 2010 01:09, Vince O'Sullivan <vjosulli...@gmail.com> wrote:
>
> >> for (Strange loop : loops)
> >>    if (loop.isStrange())
> >>        continue;
>
> >> On Aug 3, 6:23 pm, Alex <alexdmil...@yahoo.com> wrote:
> >> > The deadline for the contest will be Aug. 31st!  Give us your loops!
>
> >> > Alex
>
> >> --
> >> You received this message because you are subscribed to the Google Groups
> >> "The Java Posse" group.
> >> To post to this group, send email to java...@googlegroups.com.
> >> To unsubscribe from this group, send email to
> >> javaposse+...@googlegroups.com<javaposse%2Bunsubscribe@googlegroups .com>
> >> .
> >> For more options, visit this group at
> >>http://groups.google.com/group/javaposse?hl=en.
>
> > --
> > Kevin Wright
>
> > mail/google talk: kev.lee.wri...@gmail.com
> > wave: kev.lee.wri...@googlewave.com
> > skype: kev.lee.wright
> > twitter: @thecoda
>
> >  --
> > You received this message because you are subscribed to the Google Groups
> > "The Java Posse" group.
> > To post to this group, send email to java...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > javaposse+...@googlegroups.com<javaposse%2Bunsubscribe@googlegroups .com>
> > .

Reinier Zwitserloot

unread,
Aug 4, 2010, 10:26:12 AM8/4/10
to The Java Posse
I really like how folks keep making the argument that java sucks
because it is well documented. Only a scala fanboy would go that far.

</trollbait>


On Aug 4, 11:01 am, Kevin Wright <kev.lee.wri...@gmail.com> wrote:
> my thinking:
>
> `http:` is the label (followed by a comment that the pre-processor strips
> out)
> `do { ... } while (...)` is the labelled statement
> `continue <label>` attempts to transfer control back to the "continue
> target".  In this case, the labelled do/while loop
>
> a `do {statement} while (expression)` loops will check its expression only
> once the statement has executed normally (which it hasn't here)
> So... the loop will begin again, and continue infinitely, or until an
> exception is thrown or the JVM is terminated.
>
> No stack involved, at the level of compiled machine code it'll be jump
> instructions all the way down...
>
> The language spec covering all this is here:http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
> ( or in pdf here:http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf)
>
> For anyone still labouring under the delusion that Java is a simple
> language, it's a heavyweight document; running to 650 pages in almost 8MB
> but you only really need chapter 14 for this question :)
>
> On 4 August 2010 05:43, Kirk <kirk.pepperd...@gmail.com> wrote:
>
>
>
>
>
> > I'll be speaking there so I don't need a pass but thought it might be fun
> > to put in a puzzler.
>
> > public class StrangeLoop {
> >    public static void main(String[] args) {
> >        http://www.thestrangeloop.com
> >        do {
> >            System.out.println("Strange Loop");
> >            continue http;
> >        } while (false);
> >    }
> > }
>
> > Puzzler, infinite loop or normal termination?
>
> > Regards,
> > Kirk
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "The Java Posse" group.
> > To post to this group, send email to java...@googlegroups.com.
> > To unsubscribe from this group, send email to
> > javaposse+...@googlegroups.com<javaposse%2Bunsubscribe@googlegroups .com>
> > .
> > For more options, visit this group at
> >http://groups.google.com/group/javaposse?hl=en.
>
> --
> Kevin Wright
>

Viktor Klang

unread,
Aug 4, 2010, 10:57:42 AM8/4/10
to java...@googlegroups.com
On Wed, Aug 4, 2010 at 4:26 PM, Reinier Zwitserloot <rein...@gmail.com> wrote:
I really like how folks keep making the argument that java sucks
because it is well documented.

That made me laugh. What an euphemism! :D
 
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.

For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.




--
Viktor Klang
| "A complex system that works is invariably
| found to have evolved from a simple system
| that worked." - John Gall

Akka - the Actor Kernel: Akkasource.org
Twttr: twitter.com/viktorklang

Robert Casto

unread,
Aug 4, 2010, 11:06:13 AM8/4/10
to java...@googlegroups.com
Going back to what this thread is about, you could post a better strange loop or...

Sign up to be a volunteer. They are looking for 8-10 people to help out.

http://strangeloop2010.com/pages/volunteers
Robert Casto
www.robertcasto.com


Kevin Wright

unread,
Aug 4, 2010, 11:09:46 AM8/4/10
to Fabrizio Giudici, java...@googlegroups.com
I actually got the numbers wrong here. although the final page has 649 printed on it, acrobat informs me that the document is in fact 684 pages long,

Java (3rd Edition): 684 pages, 7932 KB
Scala (current in trunk): 191 pages, 1312 KB

Why would this be so? I can think of a few reasons:
  • Java has had longer to discover and document ambiguities
  • The Java spec contains more "boilerplate": copyright, legal notices, padding, whitespace, etc.
  • Much of what Java considers to be part of the Language in Java is library in Scala (and so out of scope for the spec)
    e.g. enums, while loops, break/continue
  • Java has *lots* of special cases that Scala does away with
    e.g. autoboxing, + operator on strings, etc.
Truth be told, it's probably all of the above...


On 4 August 2010 14:06, Fabrizio Giudici <fabrizio...@tidalwave.it> wrote:

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 8/4/10 11:01 , Kevin Wright wrote:
>
> For anyone still labouring under the delusion that Java is a
> simple language, it's a heavyweight document; running to 650 pages8

> in almost 8MB but you only really need chapter 14 for this question
> :)
>
Absolute figures are mostly worthless... comparisons help. How long
are the specs of Scala? Of course, I presume it might also depend on
the writing style.

- --
Fabrizio Giudici - Java Architect, Project Manager
Tidalwave s.a.s. - "We make Java work. Everywhere."
java.net/blog/fabriziogiudici - www.tidalwave.it/people
Fabrizio...@tidalwave.it
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkxZZdYACgkQeDweFqgUGxcviQCbBSreTUXxWeVBlLjqqLfJSSWM
VY0AnjlJLJZt25fUTVnGVZIAyB+AsTAx
=j+FW
-----END PGP SIGNATURE-----

Fabrizio Giudici

unread,
Aug 4, 2010, 1:16:01 PM8/4/10
to java...@googlegroups.com, Kevin Wright

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

On 8/4/10 17:09 , Kevin Wright wrote:
> I actually got the numbers wrong here. although the final page has
> 649 printed on it, acrobat informs me that the document is in fact
> 684 pages long,
>
> Java (3rd Edition): 684 pages, 7932 KB Scala (current in trunk):
> 191 pages, 1312 KB
>
> Why would this be so? I can think of a few reasons:
>

> * Java has had longer to discover and document ambiguities * The


> Java spec contains more "boilerplate": copyright, legal notices,

> padding, whitespace, etc. * Much of what Java considers to be part


> of the Language in Java is library in Scala (and so out of scope

> for the spec) e.g. enums, while loops, break/continue * Java has


> *lots* of special cases that Scala does away with e.g. autoboxing,
> + operator on strings, etc.
>
> Truth be told, it's probably all of the above...

Also, I'd say that Sun intention was to allow others to independently
implement the compiler (as IBM did), and in this case I presume you
have to be pretty picky. I think there's only a single Scala compiler
around, right?

- --
Fabrizio Giudici - Java Architect, Project Manager
Tidalwave s.a.s. - "We make Java work. Everywhere."
java.net/blog/fabriziogiudici - www.tidalwave.it/people
Fabrizio...@tidalwave.it
-----BEGIN PGP SIGNATURE-----
Version: GnuPG/MacGPG2 v2.0.14 (Darwin)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iEYEARECAAYFAkxZoFEACgkQeDweFqgUGxd1kACeMa5OLnib0s4JR48+XU2IiB2W
orgAn16IQ4IDXwLe3t7ESlWKSjBBYEcg
=WwvA
-----END PGP SIGNATURE-----

Kevin Wright

unread,
Aug 4, 2010, 1:31:46 PM8/4/10
to java...@googlegroups.com
Right :)

Unlike the original Java, it's open source - so if anyone wanted to add features to scalac, they'd be more likely to fork it than to start from scratch working against the spec.
Even that is highly unlikely because:
  1. scalac has a plugin mechanism for extending/changing functionality
  2. Scala offers some quite nice techniques for you to add functionality via libraries, without requiring dedicated compiler support.
    Just take a look at actors (http://www.scala-lang.org/node/242)
    or ScalaTest(http://www.scalatest.org/quick_start),
    that's all library...


--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.

Dominic Mitchell

unread,
Aug 4, 2010, 4:17:49 AM8/4/10
to java...@googlegroups.com
On Tue, Aug 3, 2010 at 6:23 PM, Alex <alexd...@yahoo.com> wrote:
The deadline for the contest will be Aug. 31st!  Give us your loops!

Sadly, I can't take credit for it, but I noticed this gem fly through my feed reader this morning.


The (C) loop in question is:
char i,x[99];for(x[98]=i=1;x[98];i++)i*=!++x[i]
-Dom

Quoll

unread,
Aug 4, 2010, 12:20:32 PM8/4/10
to The Java Posse
Well if "famous" loops that we're not writing ourselves are being
mentioned (eg. Duff's Device) then how could I not mention the loop
written by Mel Kaye on the RPC-4000?

For those not familiar with the story, see: http://catb.org/jargon/html/story-of-mel.html

Kaye wrote a loop that had no termination condition, yet it terminated
just fine. He'd taken advantage of the fact that the address and
opcode were both part of the instruction word. His loop executed an
instruction that operated on data pointed to by the address operand,
then incremented the address before looping back to execute the same
instruction again on the new data location. The data had been placed
at the top of memory, so the address would overflow when he did his
final increment. The overflow incremented the opcode, changing it to a
"jump". Since the address operand had just overflowed, it was now set
to 0, and the process jumped to address 0 where it continued
execution. (This was obviously before page guards) :-)

I'd love to write something that could challenge this piece of insane
genius, but modern languages tend to protect us from ourselves. It's
not impossible to see crazy stuff like this, but it's much rarer.

Paul Gearon

Scott Bale

unread,
Aug 4, 2010, 1:05:12 PM8/4/10
to The Java Posse
I once got "bit by byte" in the following loop:

for(byte a=Byte.MIN_VALUE; a<=Byte.MAX_VALUE; a++) {
for(byte b=Byte.MIN_VALUE; b<=Byte.MAX_VALUE; b++) {
byte[] test = new byte[] { a, b};
//do something...
}
}

When I ran this, CPU shot to 100% and I had to take down Eclipse with
extreme prejudice. Can you spot the problem?

The problem is, neither of the loops can terminate. Neither for
condition will ever become false and cause the loop to terminate,
because neither a nor b can ever grow larger than Byte.MAX_VALUE. Duh.

Kyle Renfro

unread,
Aug 4, 2010, 3:43:28 PM8/4/10
to The Java Posse
Great contest!
1 pass required.

Here is a very handy loop that *everyone* should use. ha ha.

import java.io.*;
import java.util.logging.*;

public class AddTabs {

public static void main(String[] args){

try {
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new
OutputStreamWriter(System.out));
String s = in.readLine();
while (s != null){
out.println(s.replaceAll(" ", "\t"));
s = in.readLine();
}
in.close();
out.close();
}
catch (IOException ex) {

Logger.getLogger(AddTabs.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Quoll

unread,
Aug 4, 2010, 9:15:19 PM8/4/10
to The Java Posse
Ouch, that brings back an old memory too. In my case I was using an
int, but casting to a byte (for bit-banging purposes) and failed to
see that my comparison was occurring while in byte form... leading to
exactly this problem. I thought I was safe by using an int, but
obviously incompetence can overcome any level of protection. (I mean
mine here, not yours!)

Paul

Quoll

unread,
Aug 4, 2010, 9:19:54 PM8/4/10
to The Java Posse
Well, it makes some possibly invalid assumptions, but here's one
possible loop.

import java.io.*;
public class Loop {
public static void main(String[] a) throws Exception {
if (a.length == 0) a = new String[]{"Hello World!"};
if (a[0].length() == 1) System.out.println(a[0].charAt(0));
else {
System.out.print(a[0].charAt(0));
InputStream s = Runtime.getRuntime().exec(new String[]{"java",
Loop.class.getCanonicalName(), a[0].substring(1)}).getInputStream();
int c;
while ((c = s.read()) > 0) System.out.write(c);
}
}
}

You don't need the assumptions in C, and if you're not in a system
with a VM then I'm sure that some will see that you can do something
truly scary with shared pointers. :-)

Paul

JamesJ

unread,
Aug 4, 2010, 11:36:02 PM8/4/10
to java...@googlegroups.com
Here is one that stuck in my memory.  I worked with a brilliant guy that could solve problems in about any domain electrical, mechanical etc.  When ever he programed in C he would check the compiler he was using to see what op codes it was generating.  He was always programming a layer deeper that the average guy. 

Inside of his tight multi-layered loops you would see stuff like this:

for(i=10; i--;)

It took me a few minutes the first time that I saw it to remember what each part of the for loop does and figure out what he was doing.  Turns out that with the compiler that he was using, this tricky form avoided a few more cycles.

JamesJ

Roel Spilker

unread,
Aug 5, 2010, 4:56:37 AM8/5/10
to java...@googlegroups.com
Did you use a regular expression on purpose?

> -----Oorspronkelijk bericht-----
> Van: kyler...@gmail.com [mailto:java...@googlegroups.com]
> Namens Kyle Renfro
> Verzonden: 04 August 2010 21:43
> Aan: The Java Posse
> Onderwerp: [The Java Posse] Re: Post your strangest loop and
> win (up to) 4 free passes to Strange Loop!

Viktor Klang

unread,
Aug 5, 2010, 5:04:32 AM8/5/10
to java...@googlegroups.com
Guys, I'm a bit surprised not to see any multithreaded strange loops yet.

Reinier Zwitserloot

unread,
Aug 5, 2010, 5:54:32 AM8/5/10
to The Java Posse
That'll replace spaces in string literals as well.

Josh Suereth

unread,
Aug 5, 2010, 9:40:03 AM8/5/10
to java...@googlegroups.com


   def from(n: Int): Stream[Int] =
     Stream.cons(n, from(n + 1))

   // Here's the loop...
   def sieve(s: Stream[Int]): Stream[Int] =
     Stream.cons(s.head, sieve(s.tail filter { _ % s.head != 0 }))

   def primes = sieve(from(2))
   
scala>    primes take 10 print
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, empty

Heath

unread,
Aug 5, 2010, 1:43:14 AM8/5/10
to The Java Posse
Duff's Device is my favorite.

If someone knows how to make this infinite, I'm eager to hear.

-Heath

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

public class StackOverflow {
static {
try {
Class.forName(StackOverflow.class.getName(), true, new
URLClassLoader(new URL[] { new URL("file:" + new
File(StackOverflow.class.getResource(StackOverflow.class.getName() +
".class").toURI()).getParentFile().getAbsolutePath() + "/") }, null));
} catch (Exception e) {
}
}

public static void main(String[] args) {
}
}


On Aug 3, 7:09 am, Alex <alexdmil...@yahoo.com> wrote:
> The latest Java Posse episode (<a href="http://javaposse.com/
> java_posse_317_newscast_for_july_29th_2010">#317</a>) features a short
> segment (start around 51:45) of the posse talking about the <a
> href="http://strangeloop2010.com">Strange Loop conference</a>.  The
> Java Posse are giving away four FREE (as in beer) tickets based on a
> contest.
>
> The contest is:  "Write the strangest loop" (any language is ok).  You
> should post your answer here and list the number (out of 4) you
> possibly could use.  The answer will be judged by the posse (and
> me!).
>
> I'm not sure what the deadline for the contest will be but we'll post
> that here.
>
> Give us your loops!
>
> Alex Miller

Alexey Zinger

unread,
Aug 5, 2010, 3:58:45 PM8/5/10
to java...@googlegroups.com
Surely we can figure something out with runtime bytecode emission...


From: Quoll <gea...@gmail.com>
To: The Java Posse <java...@googlegroups.com>
Sent: Wed, August 4, 2010 12:20:32 PM
Subject: [The Java Posse] Re: Post your strangest loop and win (up to) 4 free passes to Strange Loop!

Bill Robertson

unread,
Aug 9, 2010, 1:02:39 PM8/9/10
to The Java Posse
A fun one.

for(long t = 0; t < System.currentTimeMillis(); ++t) {
}

Niels Ull

unread,
Aug 10, 2010, 4:28:22 AM8/10/10
to The Java Posse
public class Main {
public static void main(String[] args) throws IOException {
String msg = "Hello ";
List<String> strings = new
ArrayList<String>(Arrays.asList(args));
try {
String s = strings.remove(0);
for (int i = 0; i >= 0; i++) {
msg += s.toCharArray()[i];
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(msg);
main(strings.toArray(new String[0]));
} catch (IndexOutOfBoundsException e) {
System.out.println("Goodbye");
}
}
}

No tickets needed - can't make it anywat

Curt Cox

unread,
Aug 31, 2010, 9:34:47 PM8/31/10
to The Java Posse
My Strange Loop submission is the "new To" Loop. I only need one
ticket.

The "new To" loop provides a looping alternative that is often
slightly more concise than the for loop. It allows you to replace:

for (Object x : new Integer[] {8,6,7,5,3,0,9}) { print("Jenny:" +
x); };

with:

new To(8,6,7,5,3,0,9) {{ print("Jenny:" + x); }};

Unlike, the standard for loop, the new To loop also accepts IteratorS
and EnumerationS:

new To(System.getProperties().keys()) {{ print(x); }};

A To is an object that implements several interfaces, so that adapters
aren't required in order use it in a variety of ways. Because it is a
Collection, it can be executed again later, along with additional
code, using a for loop.

for (Object x : to) {
// do additional stuff to x, here
}

If no additional action is to be taken on the subsequent runs, it can
simply be run as a Runnable, or called as a Callable. No matter how
the loop is executed again, any registered ObserverS are notified.
Thus, in addition to being nested like for loops, To loops can be
wired together for interleaved execution.

To tick = new To(1,2,3) {{ print("tick:" + x); }};
To tock = new To(4,5,6) {{ print("tock:" + x); }};

tick.addObserver(tock);

tick.run();

Unfortunately, despite these advantages, the current implementation
has several glaring limitations.

1) Special care must be taken to handle empty loops
2) It only supports To loops that are static classes
3) It has much more overhead and is much slower than an equivalent for
loop

Full source code is available here:
http://dl.dropbox.com/u/8066/To.java

Alex

unread,
Aug 31, 2010, 11:16:08 PM8/31/10
to The Java Posse
Thanks - I think the posse are meeting soon to determine the
winners!

Alex Miller

Kevin Wright

unread,
Sep 5, 2010, 6:32:23 PM9/5/10
to java...@googlegroups.com
Just listened to the results in podcast #322 (hereafter to be known as "the epic")
And the winners were:

#1 Joseph Darcy
#2 Curt Cox
#3 Me!
#4 Bill Robertson


I'd love to go, but find myself to be living on the wrong continent...

Enjoy your ticket Bill!


--
Kevin Wright

mail / gtalk / msn : kev.lee...@gmail.com
pulse / skype: kev.lee.wright
twitter: @thecoda

Alex

unread,
Sep 6, 2010, 12:41:01 AM9/6/10
to The Java Posse
Congrats guys! I'll follow up with the winners.

Alex Miller
http://strangeloop2010.com


On Sep 5, 5:32 pm, Kevin Wright <kev.lee.wri...@gmail.com> wrote:
> Just listened to the results in podcast #322 (hereafter to be known as "the
> epic")
> And the winners were:
>
> #1 Joseph Darcy
> #2 Curt Cox
> #3 Me!
> #4 Bill Robertson
>
> I'd love to go, but find myself to be living on the wrong continent...
>
> Enjoy your ticket Bill!
>
> --
> Kevin Wright
>
> mail / gtalk / msn : kev.lee.wri...@gmail.com

Christian Catchpole

unread,
Sep 6, 2010, 12:52:28 AM9/6/10
to The Java Posse
These 9 characters are great for producing carbon...

for(;;){}

Bill Robertson

unread,
Sep 7, 2010, 11:50:54 PM9/7/10
to The Java Posse
I'd like to thank the Alex for the ticket, the Posse for judging and
all of the hard work they do (seriously, thanks guys), Kevin, and last
but not least Nicholas Forth, inventor of the for loop.



On Sep 5, 6:32 pm, Kevin Wright <kev.lee.wri...@gmail.com> wrote:
> Just listened to the results in podcast #322 (hereafter to be known as "the
> epic")
> And the winners were:
>
> #1 Joseph Darcy
> #2 Curt Cox
> #3 Me!
> #4 Bill Robertson
>
> I'd love to go, but find myself to be living on the wrong continent...
>
> Enjoy your ticket Bill!
>
> --
> Kevin Wright
>
> mail / gtalk / msn : kev.lee.wri...@gmail.com
Reply all
Reply to author
Forward
0 new messages