A few days ago Jim Fuller asked on Twitter:
Here are my two answers in the categories: 1) Elegant; 2) Fast
These and other solutions can be found at: http://en.wikibooks.org/wiki/XQuery/Fizzbuzz
for $n in (1 to 100),
No explicit conditional if/then/else clauses are used here. No XQuery-only cpecific constructs.
This XPath 2.0 expression can be evaluated “as-is” in any XPath 2.0 host (XSLT 2.0, XQuery 1.0 or other).
for $k in 1 to 100 idiv 15 +1,
This expression could be efficient because there is no mod operator used at all.
It is a pure XPath 3.0 expression and can be evaluated “as-is” in any XPath 3.0 host (XSLT 3.0, XQuery 3.0 or other).
Kit Wallace has collected all offered solutions and on his page one can compare all of them for running times. Here is a typical screensshot (RQ-1-CW and DN-2 seem to have almost identical speed. If you repeatedly refresh this page, half of the times one of these solutions is the fastest and half of the time — the other.):
The Fizzbuzz problem was created as a test for prospective programmers.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
|DN-2||Dimitre Novatchev||A highly optimised algorithm||0.98|
|RQ-1-CW||Rob Whitby||Optimised by factoring a repeated subsequence – modified||1.01|
|CW-2||Chris Wallace||An algorithm||2.29|
|JF-1||Jim Fuller||A simple, clean algorithm||3.3|
|ML-1||Mark Lawson||A simple algorithm||3.67|
|DN-1||Dimitre Novatchev||An XPath algorithm||4.11|
|CW-1||Chris Wallace||Strings and their modulus values parameterised to support ease of modification||6.57|
|RQ-1||Rob Whitby||Optimised by factoring a repeated subsequence||failed|