title: 5318008 - Fun with Calculators

text:
# Question
Title: 5318008 - Fun with Calculators
In schools across the world, children type a number into their LCD calculator, turn it upside down and erupt into laughter after creating the word 'Boobies'. Of course, this is the most popular word, but there are many other words which can be produced.

All words must be less than 10 letters long, however (the dictionary does contain words long than this however, so you must perform a filter in your program). In this dictionary, there are some uppercase words, so convert the all words the lowercase.

Using, an English language dictionary, create a list of numbers which can be typed into an LCD calculator and makes a word. As with all code golf questions, the shortest program to complete this task wins.

For my tests, I used the UNIX wordlist, gathered by typing:

```
ln -s /usr/dict/words w.txt

```

Or alternatively, get it here.

For example, the image above was created by typing the number `35007` into the calculator and turning it upside down.

The letters and their respective numbers:

* *b*: `8`
* *g*: `6`
* *l*: `7`
* *i*: `1`
* *o*: `0`
* *s*: `5`
* *z*: `2`
* *h*: `4`
* *e*: `3`

Note that if the number starts with a zero, a decimal point is required after that zero. The number must not start with a decimal point.

I think this is MartinBüttner's code, just wanted to credit you for it :)

```
/* Configuration */

var QUESTION_ID = 51871; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";

/* App */

var answers = [], page = 1;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      if (data.has_more) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^,]+)/;

function shouldHaveHeading(a) {
  var pass = false;
  var lines = a.body_markdown.split("\n");
  try {
    pass |= /^#/.test(a.body_markdown);
    pass |= ["-", "="]
              .indexOf(lines[1][0]) > -1;
    pass &= LANGUAGE_REG.test(a.body_markdown);
  } catch (ex) {}
  return pass;
}

function shouldHaveScore(a) {
  var pass = false;
  try {
    pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
  } catch (ex) {}
  return pass;
}

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  answers = answers.filter(shouldHaveScore)
                   .filter(shouldHaveHeading);
  answers.sort(function (a, b) {
    var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
        bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  answers.forEach(function (a) {
    var headline = a.body_markdown.split("\n")[0];
    //console.log(a);
    var answer = jQuery("#answer-template").html();
    var num = headline.match(NUMBER_REG)[0];
    var size = (headline.match(SIZE_REG)||[0])[0];
    var language = headline.match(LANGUAGE_REG)[1];
    var user = getAuthorName(a);
    if (size != lastSize)
      lastPlace = place;
    lastSize = size;
    ++place;
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", user)
                   .replace("{{LANGUAGE}}", language)
                   .replace("{{SIZE}}", size)
                   .replace("{{LINK}}", a.share_link);
    answer = jQuery(answer)
    jQuery("#answers").append(answer);

    languages[language] = languages[language] || {lang: language, user: user, size: size, link: a.share_link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang > b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
```

```
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 50%;
  float: left;
}

#language-list {
  padding: 10px;
  width: 50%px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
```

# Answer
# CJam, ~~44~~ 42 bytes

```
r{el"oizehsglb"f#W%"0."a.e|N+_,B<*_W&!*r}h

```

Try it online in the CJam interpreter.

To run the program from the command line, download the Java interpreter and execute:

```
java -jar cjam-0.6.5.jar 5318008.cjam < /usr/share/dict/words

```

### How it works

```
r            e# Read a whitespace-separated token from STDIN.
{            e# While loop:
 el          e#   Convert to lowercase.
 "oizehsglb" e#   Push that string.
 f#          e#   Get the index of each character from the input in that string.
             e#   This pushes -1 for "not found".
 W%          e#   Reverse the resulting array.
 "0."a       e#   Push ["0."].
 .e|         e#   Vectorized logical NOT. This replaces an initial 0 with "0.".
 N+          e#   Append a linefeed.
 _,B<*       e#   Repeat the array (array.length < 11) times.
 _W&!*       e#   Repeat the array !(array.intersection(-1)) times.
 r           e#   Read a whitespace-separated token from STDIN.
}h           e# If the token is not empty, repeat the loop.

```
> 7 votes

# Answer
# Bash + coreutils, 54

Again, thanks to @TobySpeight for the golfing help.

```
rev|tr oizehsglb 0-8|sed '/.\{11\}\|[^0-9]/d;s/^0/&./'

```

Input wordlist is taken from STDIN:

```
$ ./5318008.sh < /usr/share/dict/words | head
8
38
338
5338
638
5638
36138
31738
531738
7738
$

```
> 9 votes

# Answer
# Python 2, ~~271~~ ~~216~~ ~~211~~ 205 Bytes

This is the only idea I've had so far.. I will update this once I think of something else! I assumed we needed to read from a file, but if not let me know so I can update :)

*Big thanks to Dennis for saving me 55 bytes :)*

*Also thanks to Sp3000 for saving 6 bytes :)*

```
d,f,g='oizehsglb',[x.lower()for x in open('w.txt').read().split('\n')if len(x)<10],[]
for x in f:
 c=x[::-1]
 for b in d:c=c.replace(b,`d.find(b)`)
 g=[g,g+[['0.'+c[1:],c][c[0]!='0']]][c.isdigit()]
print g

```
> 6 votes

# Answer
# JavaScript (ES7), 73 bytes

This can be done in ES7 a mere 73 bytes:

```
s=>[for(w of s)'oizehsglb'.search(w)].reverse().join``.replace(/^0/,'0.')

```

Ungolfed:

```
var b = function b(s) {
    return s.length < 10 && /^[bglioszhe]*$/.test(s) ? s.replace(/./g, function (w) {
        return 'oizehsglb'.search(w);
    }).reverse().join('').replace(/^0/, '0.') : '';
};

```

Usage:

```
t('hello'); // 0.7734
t('loose'); // 35007
t('impossible'); //

```

Function:

```
t=s=>                       // Create a function 't' with an argument named 's'
   [                        // Return this array  comprehension
     for(i of s)            // Loops through each letter in the string
     'oizehsglb'.search(w)  // Converts it to it's corresponding number
   ]
  .reverse().join``         // Reverse the array and make it a string
  .replace(/^0/,'0.')       // If the first character is a 0, add a decimal after it

```

---

I ran this on the UNIX wordlist and have put the results in a paste bin:

# Results

The code used to obtain the results *on Firefox*:

```
document.querySelector('pre').innerHTML.split('\n').map(i => t(i.toLowerCase())).join('\n').replace(/^\s*[\r\n]/gm, '');

```
> 6 votes

# Answer
# Python 2, 121 bytes

```
for s in open("w.txt"):
 L=map("oizehsglb".find,s[-2::-1].lower())
 if-min(L)<1>len(L)-9:print`L[0]`+"."[L[0]:]+`L`[4::3]

```

Assumes that the dictionary file `w.txt` ends with a trailing newline, and has no empty lines.
> 5 votes

# Answer
# GNU sed, 82

(including 1 for `-r`)

Thanks to @TobySpeight for the golfing help.

```
s/$/:/
:
s/(.)(:.*)/\2\1/
t
s/://
y/oizehsglb/012345678/
/.{11}|[^0-9]/d;s/^0/&./

```

Input wordlist is taken from STDIN:

```
$ sed -rf 5318008.sed /usr/share/dict/words | tail
3705
53705
1705
0.705
50705
5705
505
2
0.02
5002
$

```
> 3 votes

# Answer
# Python 2, ~~147~~ ~~158~~ 156 bytes

I was missing this '0.' requirement. Hope now it works allright.

**edit**: Removed ".readlines()" and it still works ;p

**edit2**: Removed some spaces and move print to the 3rd line

**edit3**: Saved 2 bytes thanks to Sp3000 (removed space after print and changed 'index' to 'find')

```
for x in open("w.txt"):
 a="oizehsglb";g=[`a.find(b)`for b in x[::-1].lower()if b in a]
 if len(g)==len(x)-1<10:
  if g[0]=="0":g[0]="0."
  print"".join(g)

```
> 2 votes

# Answer
# C, 182 172  169/181 172 bytes

```
char*l="oizehsglb",S[99],*s,*t;main(x){for(;t=S+98,gets(S);){for(s=S;*s;s++)if(x=strchr(l,*s|32))*--t=48+x-(int)l;else break;*t==48?*t--=46,*t=48:0;*s||s-S>10?0:puts(t);}}

```

Expanded

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *l="oizehsglb",S[99],*s,*t;

main(int x, char **argv)
{
    for (;t=S+98,gets(S);){
        for (s=S;*s;s++)
            if (x=strchr(l,*s|32))
                *--t=48+x-(int)l;
            else
                break;
        if (*t==48) {       // '0'
            *t--=46;        // '.'
            *t=48;  // '0'
        }

        if (!*s && s-S <= 10)
            puts(t);
    }
}

```

using the linked words.txt, with lower case conversion:

```
$ ./a.out  < words.txt  | tail
2212
0.2
0.802
0.602
7702
37702
0.02
321607002
515002
0.02002

$ ./a.out < words.txt   | wc -l
 550

```
> 1 votes

# Answer
# Ruby 2, ~~88~~ 86 bytes

```
x="oizehsglb"
puts$_.tr(x,"0-8").reverse.sub /^0/,"0." if$_.size<11&&$_.delete(x)<?A

```

Byte count includes 2 for the `ln` options on the command line:

```
$ ruby -ln 5318008.rb wordlist.txt

```
> 1 votes

# Answer
# Python 2, ~~184~~ 174 bytes

```
for s in open('w.txt'):
 try:a=''.join(map(lambda c:dict(zip('bglioszhe','867105243'))[c],s[:-1][::-1]));a=[a,'0.'+a[1:]][a[0]=='0'];print['',''.join(a)][len(s)<11]
 except:0

```
> 1 votes

# Answer
# Java, 208 200 176 bytes

```
String f(char[] w){String o="",l="oizehsglb";for(int i=w.length;i>0;i--)o+=l.indexOf(w[i-1]|32);if(o.contains("-")||o.length()>8)o="  ";return o.charAt(0)+"."+o.substring(1);}

```

Expanded

```
String f(char[] w)
{
    String o = "", l = "oizehsglb";
    for(int i = w.length; i > 0; i--)
        o+=l.indexOf(w[i-1]|32);
    if(o.contains("-")||o.length() > 8)
        o = "  ";
    return o.charAt(0) + "." + o.substring(1);
}

```

It always adds the decimal, and when invalid returns " . ". But otherwise works like it should. :P

Thanks @LegionMammal978!
> 1 votes

# Answer
# Haskell, 175 bytes without imports (229 bytes with imports)

Relevant code (say in File Calc.hs):

```
import Data.Char(toLower)
import Data.Maybe(mapMaybe)
s="oizehsglb\n"
g('0':r)="0."++r
g x=x
main=mapM_(putStrLn.g.reverse.mapMaybe(`lookup`zip s['0'..'8'])).filter(\l->length l<10&&all(`elem`s)l).lines.map toLower=<<getContents

$ cat /usr/share/dict/words | runghc Calc.hs

```
> 1 votes

---
Tags: code-golf
---


title: Best place for learning GolfScript?

text:
# Question
Title: Best place for learning GolfScript?
It looks like a fun language, but the official site is down and the EsoLangs page doesn't explain it quite well and looks like it's missing stuff. Is there anywhere that the language is documented?

# Answer
> 8 votes
A cached copy of the offical site is available on the Internet Archive's Way Back Machine.

# Answer
> 4 votes
GolfScript is a nice language, but, as you already said, the official webpage is down. While I don't claim to know the future, this probably means that no bugs will be fixed and no new features will be implemented. In fact, the latest version of the Ruby interpreter was released in 2013.

GolfScript also has a few annoying quirks (e.g., no character type), is **very** slow and bound to lose in contests where you'd need to use commands such as `base` or `print`, which are simply too long for a golfing language.

Where am I going with this? Learn CJam instead!

CJam is inspired by GolfScript, so almost everything you can do in GolfScript, you can do in CJam as well.

But:

---
Tags: tips, golfscript
---


title: Chinese Checkers longest move

text:
# Question
Title: Chinese Checkers longest move
In Chinese Checkers, a piece can move by hopping over any other piece, or by making a sequence of such hops. Your task is to find the longest possible sequence of hops.

# Input

A sequence of 121 zeroes or ones, each representing a place on a board. A zero means the place is empty; a one means the place is occupied. Positions are listed from left to right; top to bottom. For example, the input of this setup would be

```
1011110011000001000000000000000000000000100000000001000000000000000000000000000001000000000000000000000001000001100111111

```

Explanation:

> The top-most place is occupied by a green piece, so the first digit in the input is `1`. The second row has one empty position and then one occupied position, so `01` comes next. The third row is all occupied, so `111`. The fourth row has two empty and two occupied spaces (going left to right), so `0011`. Then comes five `0`'s, a `1`, and seven `0`'s for the next row, and so on.

Like in that setup, there is a corner pointing straight up. There may be any number of pieces on the board (from 1 to 121). Note that pieces of different colors are not represented differently.

# Output

The maximum length of a legal hop, using any piece on the board. You may not visit the same place more than once (including the starting and ending positions). However, you may hop over the same piece more than once. If there is no legal hop, output `0`. Do not consider whether there exists a legal non-hop move.

For example, the output to the setup described above is `3`.

Input and output may be done through stdin and stdout, through command-line arguments, through function calls, or any similar method.

# Test Cases

Input:

```
0100000010000000000000000100000000000000000000000000000001010010000000000000000000000101000000000000000000100000000100001

```

Output: `0` (no two pieces are next to each other)

---

Input:

```
0000000000111100000000011100000000011000000000100000000000000000000000000000000000000000000000000000000000000000000000000

```

Output: `1` (initial setup for one player in top-left corner)

# Answer
> 2 votes
## Perl, ~~345~~ 322

**Edit:** golfed, slightly.

More test cases would be nice, but for now it looks like it works. I'll add comments later if necessary. With newlines and indentation for readability:

```
$_=<>;
$s=2x185;
substr$s,(4,22,unpack'C5(A3)*','(:H[n129148166184202220243262281300')[$i++],0,$_
    for unpack A.join A,1..4,13,12,11,10,9..13,4,3,2,1;
$_=$s;
sub f{
    my(@a,%h)=@_;
    $h{$_}++&&return for@a;
    $-+=$#a>$-;
    $s=~/^.{$a[0]}$_/&&f($+[1],@a)
        for map{("(?=.{$_}1.{$_}(0))","(?<=(0).{$_}1.{$_}.)")}0,17,18
}
f$+[0]while/1/g;
print$-

```

# Answer
> 2 votes
# C,~~262~~ 260

**Golfed code** (debugging code and unnecessary whitespace removed. Changed from input via stdin to input via command line, and took advantage of the opportunity to declare variable i there. Latest edit: code moved into brackets of `for` loops to save two semicolons.)

```
t[420],j,l,x,y;f(p,d){int z,q,k;for(k=6;k--;t[q]&!t[p+z]?t[q]=0,f(q,d+1),t[q]=1:0)z="AST?-,"[k]-64,q=p+z*2;l=d>l?d:l;}main(int i,char**s){for(i=840;i--;x>3&y>5&x+y<23|x<13&y<15&x+y>13?i>420?t[i-420]=49-s[1][j++]:t[i]||f(i,0):0)x=i%20,y=i/20%21;printf("%d",l);}

```

**Explanation**

This relies on a 20x21 board which looks like this, initially filled with zeroes when the program starts (this ASCII art was generated by a modified version of the program, and as the `i` loop counts downwards, zero is in the bottom right corner):

```
....................
....................
...............#....
..............##....
.............###....
............####....
.......#############
.......############.
.......###########..
.......##########...
.......#########....
......##########....
.....###########....
....############....
...#############....
.......####.........
.......###..........
.......##...........
.......#............
....................
....................

```

Loop `i` runs through this board twice, using x and y to calculate whether a square actually belongs to the checkerboard or not (this requires 6 separate inequalities in x and y.)

If it does, the first time round it fills the squares, putting a `0` (falsy) for a `1` (occupied) and a `1` (truthy) for a `0` (unoccupied). This inversion is important, because all out-of-bounds squares already contain a 0, which means they resemble occupied squares and it is clear they can't be jumped into, without the need for a specific check.

The second time round, if the square is occupied (contains 0) it calls the function `f` that searches for the moves.

`f` searches recursively in the 6 possible directions encoded by +/-1 (horizontal), +/-20 (vertical) and +/-19 (diagonal) encoded in the expression `"AST?-,"[k]-64`. When it finds a hit, it sets that cell to a 0 (occupied) before calling itself recursively, then sets it back to 1 (empty) when the function is returned. The cell value must be changed before the recursive call to prevent hopping into that cell more than once.

**Ungolfed code**

```
char s[999];                           //input string.
t[420],i,j,l,x,y;                      //t=board. i=board counter, j=input counter. l=length of longest hop found so far.

f(p,d){                                //p=position, d= recursion depth.
  //printf("%d,%d ",p,d);              //debug code: uncomment to show the nodes visited.
  int k,z,q;                           //k=counter,z=displacement,q=destination
  for(k=6;k--;)                        //for each direction
    z="AST?-,"[k]-64,                  //z=direction
    q=p+z*2,                           //q=destination cell
    t[q]&!t[p+z]?                      //if destination cell is empty (and not out of bounds) and intervening cell is full
      t[q]=0,f(q,d+1),t[q]=1           //mark destination cell as full, recurse, then mark it as empty again.
      :0;
  l=d>l?d:l;                           //if d exceeds the max recorded recursion depth, update l
}

main(){
  gets(s);                             //get input
  for(i=840;i--;)                      //cycle twice through t
    x=i%20,                            //get x
    y=i/20%21,                         //and y coordinates
    x>3&y>5&x+y<23|x<13&y<15&x+y>13?   //if they are in the bounds of the board
      i>420?
        t[i-420]=49-s[j++]             //first time through the array put 0 for a 1 and a 1 for a 0 ('1'=ASCII49)
        :t[i]||f(i,0)                  //second time, if t[i]=0,call f().
       //,puts("")                     //puts() formats debug output to 1 line per in-bounds cell of the board
      :0;
  printf("%d",l);                      //print output
}

```

---
Tags: code-golf, board-game, hexagonal-grid
---


# Question
Title: Implement String.prototype.toLowerCase()
**Implement `String.prototype.toLowerCase()`**

**Description**

The `toLowerCase` method returns the value of the string converted to `lowercase`. toLowerCase does not affect the value of the string itself.

**Conditions** Let count chars inside function and ignore all bootstrap code:

```
String.prototype.toLowerCase = function(){
  // code that count here
}

```

Other languages are welcome but JavaScript implemantation is target of this question. Let's just focus on ASCII charachters .

Example input and output:

```
"sOmeText".toLowerCase(); => "sometext"

```

Example implementation:

```
String.prototype.toLowerCase = function(){
  return this.split('').map(function(c){
     var cc = c.charCodeAt(0);
     if (cc > 64 && cc < 91) {
        return String.fromCharCode(cc + 32);
     }
     return c;
  }).join('');
}

```

# Answer
> 5 votes
## Javascript 70 68

Building from @grc's answer:

```
for(s=i='';c=this[i++];s+=(parseInt(c,36)||c).toString(36));return s

```

Convert character to integer then back (works since `Number.toString(36)` will always be lowercase)

Test case: http://jsfiddle.net/Vh2TW/2/

input:

```
console.log('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~`-=_+{}[]:;\\\'\"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz'.toLowerCase())

```

output:

```
abcdefghijklmnopqrstuvwxyz1234567890~`-=_+{}[]:;\'"<>,.?/!@#$%^&*()abcdefghijklmnopqrstuvwxyz

```

**Update:** -2 characters, thanks @copy

# Answer
> 4 votes
## Bash, 10

Doesn't interface with javascript very well, but it works for everyday purposes.

```
tr A-Z a-z

```

Also, it's shorter than golfscript. (Booyah!)

---

**Example Input:**

```
echo "Hello World, asDFghJkL0123" | tr A-Z a-z

```

**Output:**

```
hello world, asdfghjkl0123

```

# Answer
> 2 votes
## Golfscript, 17

```
{..64>\91<*32*|}%

```

# Answer
> 2 votes
## J, 25

```
toLowerCase =: u:@(+32*91&>*64&<)@(3&u:)

```

Converting to numbers `(3&u:)` and back `u:` is quite uneasy.

# Answer
> 1 votes
## Javascript, 86

```
String.prototype.toLowerCase = function () {
    s="";for(i=0;c=this.charCodeAt(i++);s+=String.fromCharCode(c>64&c<91?c+32:c));return s
};

```

# Answer
> 1 votes
## Python (45)

`l=lambda x:''.join(chr(ord(i)+('@'<i<'[')*32)for i in x)`

Pseudocode:

```
l=func(x) {
  return toString( iterate(i in x) { chr(ord(i) + IsUppercase(i) * 32) } )
}

```

Explanation:
`('@'<i<'[')*32)`: `IsUppercase.` '@' - 64, 'A' - 65, 'Z' - 90, '\[' - 91: If `64<ord(i)<91`, then return True and multiply it by 32 (to get `32`).

# Answer
> 0 votes
## VBA - 77 82

```
Function l(s)
'Counting only the stuff between Function and End
For x=1 To Len(s):m=Mid(s,x,1):l=l & IIf(m Like"[A-Z]",Chr(Asc(m)+32),m):Next
End Function

```

# Answer
> 0 votes
# Ruby: 32 characters

```
s.gsub(/[A-Z]/){($&.ord+32).chr}

```

Sample run:
(In 35 characters it can be made a method of `String` class, to work just as the JavaScript sample.)

```
irb(main):001:0> class String
irb(main):002:1>   def toLowerCase
irb(main):003:2>     self.gsub(/[A-Z]/){($&.ord+32).chr}
irb(main):004:2>   end
irb(main):005:1> end
=> nil
irb(main):006:0> "sOmeText".toLowerCase
=> "sometext"

```

# Answer
> 0 votes
### javascript 76 chars:

```
replace(/[A-Z]/g,function(b){return String.fromCharCode(b.charCodeAt()+32)})

```

Here's the full function:

```
String.prototype.toLowerCase = function () {
    return this.replace(/[A-Z]/g, function(b){
        return String.fromCharCode(b.charCodeAt()+32)
    });
}

```

# Answer
> 0 votes
# Julia, 49 chars

```
L(s)=ascii([s[i]+32(64<s[i]<91)for i=1:endof(s)])

```

for all chars s\[i\] if 64 \< s\[i\] \< 91 is true, add 32 to the ASCII character point (32\*true=32). If it’s false, then (32\*false=0), and nothing is changed.

example:

```
julia> str
"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#abcdefghijklmnopqrstuvwxyz~"

julia> L(str)
"abcdefghijklmnopqrstuvwxyz1234567890!@#abcdefghijklmnopqrstuvwxyz~"

```

The default method in Julia is lowercase(str)

```
julia> lowercase(str)
"abcdefghijklmnopqrstuvwxyz1234567890!@#abcdefghijklmnopqrstuvwxyz~"

```

the difference in timing and memory allocation:

```
julia> @time L(str)
elapsed time: 1.0263e-5 seconds (792 bytes allocated)

julia> @time lowercase(str)
elapsed time: 6.693e-6 seconds (224 bytes allocated)

```

---
Tags: code-golf, javascript
---


title: Meta quine checker

text:
# Question
Title: Meta quine checker
This challenge, if you accept it, is to write three functions or programs A, B, and C:

* A is a quine that outputs all of A,B and C (which is also the whole content of the code in your submission).
* B takes a parameter F and checks whether it is such a quine (outputting FBC), or doing something different.
* C takes a parameter G and checks whether G possibly works like B (checking whether F outputs FGC). It is impossible to decide whether a function is a quine checker, so let's do something simpler:
    + It must return truthy if G is valid for B.
    + It must return falsey if G returns falsey for all valid quines, or G returns truthy for all valid non-quines.
    + It can return anything, crash or not terminate, etc, if it is any of the other cases.

Note that B is possible. A and F doesn't have any input, so you can just run them and check the result.

### Rules

* There should be some way to tell which parts are A, B and C from the output of A. For example: each has one line, or they are recognized as three functions in the interpreter.
* Each function should run with only the definition of itself, not your complete code.
* You can use a function/program or its source code, or a pair of both as the input of B (or G) and C.
* You can redefine truthy/falsey to a subset of those values. You can also consistently require F returning some type you choose, like a single string.
* You can require A, B, F and G, if they are called with valid parameters, consistently don't have some types of other inputs or side effects you choose, such as accessing global variables, or reading stdin, etc.
* You can also assume F and G, if they are called with valid parameters, always terminate.
* F should work in the same condition as A. So it cannot depend on B or C or another variable's existence, unless that variable is defined in its own part in its output.
* No functions or programs can read its own source code.
* This is code-golf, shortest code (which is the output of A) in bytes wins.

# Answer
> 1 votes
# CJam, 254 bytes

An example answer, not golfed.

```
{{['{\"_~}{{[1$'{@\"_~}"{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}_``1>W<"\"]s\~=}_~}"@]s}_~}{{[1$'{@"_~}{{[\"_~}\"2$+'{@\"_~}\"]s`\"{{['{\\\\\"\+\"]s}_~}\"+~1$~{L}@~!&}_~}"]s\~=}_~}{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}

```

The 3 functions are:

```
{{['{\"_~}{{[1$'{@\"_~}"{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}_``1>W<"\"]s\~=}_~}"@]s}_~}

```

```
{{[1$'{@"_~}{{[\"_~}\"2$+'{@\"_~}\"]s`\"{{['{\\\\\"\+\"]s}_~}\"+~1$~{L}@~!&}_~}"]s\~=}_~}

```

```
{{["_~}"2$+'{@"_~}"]s`"{{['{\\"\+"]s}_~}"+~1$~{L}@~!&}_~}

```

A and F take no parameters and return a string. B, G and C take a CJam block as parameter and return 1 for truthy, or 0 for falsey.

---
Tags: code-golf, quine
---


title: Build a one-word search generator

text:
# Question
Title: Build a one-word search generator
The word `BANANA` appears exactly once in this word search:

```
B A N A A N B B
A B A N A B A N
A N A B N N A A
N N B A A A N N
N A A N N N B A
A N N N B A N A
N A A B A N A N
B A N A N B B A

```

The word search above contains only one occurrence of the word `BANANA` looking up, down, left, right, or diagonally, but it has lot of similar words, like `BANANB`, `BANNANA`, `BNANA`, etc.

Your job is to build a program that will generate infuriating word searches like this one.

Your program will take as input:

* One word, in all capital letters, containing from three to seven unique letters with at least four letters total.
* One number, to represent the dimension of the square grid for the word search. The number must be at least the number of letters in the word.

And then, output a word search using only the letters in the word, that contains *exactly one* occurrence of the input word, and as many *infuriators* as possible.

An infuriator is defined as a string that has a Damerau-Levenshtein distance of one from the target word and begins with the same letter as the word. For `BANANA`, this would include words like:

* `BANBNA`, where one of the letters was substituted.
* `BANNANA` or `BANAANA`, where an extra letter was added.
* `BANAN`, `BNANA`, where a letter was deleted, but not `ANANA`, since there's no longer a `B`.
* `BAANNA` or `BANAAN`, where two consecutive letters were switched.

When counting infuriators on a word search grid, they may overlap, but you cannot count a large string if it completely contains a smaller string you've already counted, or vice versa. (If you have `BANANB`, you can't count it again if you've already counted the `BANAN` or the backwards `BNANA` inside it.) You also cannot count any strings that completely contain or are completely contained by the target word itself (you cannot count the specific `BANAN` that is part of `BANANA`, nor `BANANAA` or `BANANAN`.)

---

Your program will be tested on a specific word list composed of the words that fit the input word requirement (to be given later once I've generated it), on a grid size equal to double the length of the word, and will be scored on the number of infuriators present in each grid. Please post your results for the inputs `BANANA 12`, `ELEMENT 14`, and `ABRACADABRA 22` for verification.

# Answer
# JavaScript

Bonus: You can seed the Word search. Default seed is: "codechallenge"

```
ws = document.getElementById("word_search");
Math.seedrandom("CodeChallenge");
m = -1;
n = 0;
x = 0;
var addMethod = 1;
var addFail = 0;
var final = false;

function reset() {
    ws.innerHTML = '';
}

function write(str1) {
    ws.innerHTML += "<h1>" + str1 + "</h1>";
}

document.getElementById("word").oninput = function () {
    document.getElementById("word").value = document.getElementById("word").value.toUpperCase();
};

document.getElementById("size").onblur = function () {

    if (document.getElementById("word").value.length > document.getElementById("size").value) {
        document.getElementById("size").value = document.getElementById("word").value.length;
    }
    if (document.getElementById("word").value == "") {
        document.getElementById("size").value = "0";
    }
};

document.getElementById("go").onclick = function () {
    reset();
    word = document.getElementById("word").value.toUpperCase();
    size = document.getElementById("size").value;
    if (size == 0) {
        word = "BANANA";
        return;
    }
    data = new Array();
    for (var i = 0; i < size; i++) {
        data[i] = new Array();
        for (var j = 0; j < size; j++) {
            data[i][j] = "NONE";
        }
    }

    while (add(dld(word)))
    for (var i = 0; i < size; i++) {
        for (var j = 0; j < size; j++) {
            if (data[i][j] == "NONE") {
                data[i][j] = word.charAt(Math.floor(Math.random() * word.length))
            }
            if (data[i][j] == "") {
                data[i][j] = word.charAt(Math.floor(Math.random() * word.length))
            }
        }
    }

    finalput(Math.floor(Math.random() * size), Math.floor(Math.random() * size), word);

    for (var i = 0; i < size; i++) {
        write(data[i].toString().replace(/,/g, ""));
    }

};

function test(x1, y1, x2, y2) {
    if (x2 > size || x2 < 0 || y2 > size || y2 < 0 || x1 > size || x1 < 0 || y1 > size || y1 < 0) {
        return false;
    }
    try {
        switch (true) {
            case x1 == x2 && y1 < y2:
                for (var c = y1; c < y2; c++) {
                    if (data[x1][c] != "NONE") {
                        return false;
                    }
                }
                break;
            case x1 == x2 && y1 > y2:
                for (var c = y2; c < y1; c++) {
                    if (data[x1][c] != "NONE") {
                        return false;
                    }
                }
                break;
            case y1 == y2 && x1 < x2:
                for (var c = x1; c < x2; c++) {
                    if (data[y1][c] != "NONE") {
                        return false;
                    }
                }
                break;
            case y1 == y2 && x2 < x1:
                for (var c = x2; c < x1; c++) {
                    if (data[y1][c] != "NONE") {
                        return false;
                    }
                }
                break;
            case y1 != y2 && x1 != x2:
                var x = x1;
                var y = y1;
                while (true) {
                    if (x == x2 || y == y2) {
                        return true;
                    }
                    if (data[x][y] != "NONE") {
                        return false;
                    }
                    if (x < x2) {
                        x++;
                    } else {
                        x--;
                    }
                    if (y < y2) {
                        y++;
                    } else {
                        y--;
                    }
                }
                break;
        }
    } catch (err) {
        return false;
    }
    return true;
}

function put(arg1, arg2, str1) {
    var w = Math.floor(Math.random() * 8) + 1;
    for (var l = 0; l < 8; l++) {
        switch (w) {
            case 1:
                //Right
                if (test(arg1, arg2, arg1, arg2 + str1.length)) {
                    for (var h = arg2; h < arg2 + str1.length; h++) {
                        data[arg1][h] = str1.charAt(h - arg2);
                    }
                } else {
                    w++;
                }
                break;
            case 2:
                if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
                    var g = arg1 - 1;
                    var h = arg2 - 1;
                    var i = -1;
                    while (i < str1.length) {
                        g++;
                        h++;
                        i++;
                        data[g][h] = str1.charAt(i);
                    }
                } else {
                    w++;
                }
                break;
            case 3:
                //Down
                if (test(arg1, arg2, arg1 + str1.length, arg2)) {
                    for (var h = arg1; h < arg1 + str1.length; h++) {
                        data[h][arg2] = str1.charAt(h - arg1);
                    }
                } else {
                    w++;
                }
                break;
            case 4:
                if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
                    var g = arg1 + 1;
                    var h = arg2 - 1;
                    var i = -1;
                    while (i < str1.length) {
                        g--;
                        h++;
                        i++;
                        data[g][h] = str1.charAt(i);
                    }
                } else {
                    w++;
                }
                break;
            case 5:
                //Left
                if (test(arg1, arg2, arg1, arg2 - str1.length)) {
                    for (var h = arg2; h > arg2 - str1.length; h--) {
                        data[arg1][h] = str1.charAt(Math.abs(h - arg2));
                    }
                } else {
                    w++;
                }
                break;
            case 6:
                if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
                    var g = arg1 + 1;
                    var h = arg2 + 1;
                    var i = -1;
                    while (i < str1.length) {
                        g--;
                        h--;
                        i++;
                        data[g][h] = str1.charAt(i);
                    }
                } else {
                    w++;
                }
                break;
            case 7:
                //UP
                if (test(arg1, arg2, arg1 - str1.length, arg2)) {
                    for (var h = arg1; h > arg1 - str1.length; h--) {
                        data[h][arg2] = str1.charAt(Math.abs(h - arg1));
                    }
                } else {
                    w++;
                }
                break;
            case 8:
                if (test(arg1, arg2, arg1 + str1.length, arg2 + str1.length)) {
                    var g = arg1 - 1;
                    var h = arg2 + 1;
                    var i = -1;
                    while (i < str1.length) {
                        g++;
                        h--;
                        i++;
                        data[g][h] = str1.charAt(i);
                    }
                } else {
                    w++;
                }
                break;
        }
    }
}

function finalput(arg1, arg2, str1) {
    if (final == false) {
        try {
            var w = Math.floor(Math.random() * 8) + 1;
            console.log(arg1 + "," + arg2 + "," + w);
            for (var l = 0; l < 8; l++) {
                switch (w) {
                    case 1:
                        //Right

                        for (var h = arg2; h < arg2 + (str1.length - 1); h++) {
                            data[arg1][h] = str1.charAt(h - arg2);
                            if(h<0){throw "err";}
                        }

                        break;
                    case 2:

                        var g = arg1 - 1;
                        var h = arg2 - 1;
                        var i = -1;
                        while (i < str1.length - 1) {
                            g++;
                            h++;
                            i++;
                            data[g][h] = str1.charAt(i);
                            if(h<0){throw "err";}
                        }

                        break;
                    case 3:
                        //Down

                        for (var h = arg1; h < arg1 + (str1.length - 1); h++) {
                            data[h][arg2] = str1.charAt(h - arg1);
                            if(arg2<0){throw "err";}
                        }

                        break;
                    case 4:

                        var g = arg1 + 1;
                        var h = arg2 - 1;
                        var i = -1;
                        while (i < str1.length - 1) {
                            g--;
                            h++;
                            i++;
                            data[g][h] = str1.charAt(i);
                            if(h<0){throw "err";}
                        }

                        break;
                    case 5:
                        //Left

                        for (var h = arg2; h > arg2 - (str1.length - 1); h--) {
                            data[arg1][h] = str1.charAt(Math.abs(h - arg2));
                            if(h<0){throw "err";}
                        }

                        break;
                    case 6:

                        var g = arg1 + 1;
                        var h = arg2 + 1;
                        var i = -1;
                        while (i < str1.length - 1) {
                            g--;
                            h--;
                            i++;
                            data[g][h] = str1.charAt(i);
                            if(h<0){throw "err";}
                        }

                        break;
                    case 7:
                        //UP

                        for (var h = arg1; h > arg1 - (str1.length - 1); h--) {
                            data[h][arg2] = str1.charAt(Math.abs(h - arg1));
                            if(arg2<0){throw "err";}
                        }

                        break;
                    case 8:

                        var g = arg1 - 1;
                        var h = arg2 + 1;
                        var i = -1;
                        while (i < str1.length - 1) {
                            g++;
                            h--;
                            i++;
                            data[g][h] = str1.charAt(i);

                            if(h<0){throw "err";}
                        }

                        break;
                }
            }
            final = true;
        } catch (err) {
            console.count("Anwser Fail");
            setTimeout(finalput(Math.floor(Math.random() * (size - (word.length * 2))) + word.length, Math.floor(Math.random() * (size - (word.length * 2))) + word.length, str1),50);
        }
    }

    return arg1 + "," + arg2 + "," + w;
}

function add(str1) {
    switch (addMethod) {
        case 1:
            if (typeof x == "undefined") {
                var x = Math.floor(Math.random() * size + 1);
                var y = Math.floor(Math.random() * size + 1);
            }
            try {
                while (data[x][y] != "NONE" && addFail <= 10) {
                    x = Math.floor(Math.random() * size + 1);
                    y = Math.floor(Math.random() * size + 1);
                    addFail++;
                }
            } catch (err) {
                return true;
                addFail++;
            }
            if (addFail == 11) {
                addMethod = 2;
                return add(str1);
            }
            try {
                put(x, y, str1);
            } catch (err) {
                return true;
            }
            addFail = 0;
            return true;
            break;
        case 2:
            m++;
            if (m == size) {
                m = 0;
                n++;
            }
            if (n == size) {
                addMethod = 3;
                return add(str1);
            }
            try {
                if (data[n][m] == "NONE") {
                    put(n, m, str1);
                }
            } catch (err) {
                return true;
            }

        case 3:
            for (var i = 0; i < size; i++) {
                for (var j = 0; j < size; j++) {
                    if (data[i][j] == "NONE") {
                        data[i][j] = str1.charAt(Math.floor(Math.random() * str1.length));
                    }
                }
            }
            return false;
    }
}

function dld(str1) {
    var result = "";
    switch (Math.floor(Math.random() * 4)) {
        case 0:
            //replace one letter
            var q = Math.floor(Math.random() * (word.length - 1)) + 1;
            result = word.slice(0, q) + word.charAt(Math.floor(Math.random() * word.length)) + word.slice(q + 1, word.length);
            break;
        case 1:
            //Add one letter
            var q = Math.floor(Math.random() * (word.length - 1)) + 1;
            result = word.slice(0, q) + word.charAt(Math.floor(Math.random() * word.length)) + word.slice(q, word.length);
            break;
        case 2:
            //Delete letter
            var q = Math.floor(Math.random() * (word.length - 1)) + 1;
            result = word.slice(0, q) + word.slice(q + 1, word.length - 1);
            break;
        case 3:
            var q = Math.floor(Math.random() * (word.length - 1)) + 1;
            result = word.slice(0, q) + word.charAt(q + 1) + word.charAt(q) + word.slice(q + 2, word.length);
            break;
    }
    if (result.search(str1) != -1) {
        return dld(str1);
    }
    return result;
}
```

```
<script src="http://cdnjs.cloudflare.com/ajax/libs/seedrandom/2.3.10/seedrandom.min.js"></script>
<div id="word_search" style="line-height: 10%;font-family:'Courier New', Courier, monospace"></div>
<input type="text" id="word" value="BANANA" placeholder="BANANA"></input>
<input type="number" id="size" value="12" placeholder="Size"></input>
<input type="button" id="go" value="Go!"></input>
```

BANANA - 12:

```
AANananabABA
BNBAAANNNNAB
NABNAAANANNA
BAAABNNNNANB
BAANAANAAAAA
NABANANBNNBN
ABBAANBBAAAN
BNANBNBAAAAA
AANAANAANNAA
BNBNBBBNAANA
ABBNABBBANNB
ABNBAAAABNNA

```

ELEMENT - 14:

```
MEEMMLNLETELEN
LLENNMENEEMEEE
MEMELMEELTELEN
NNMEEEEETNTLNM
TLLEMTETNMNEEE
EELEELLENENTTE
EELMEMELMMLTTE
EEMNLENeTEENLN
EEEETElELEEEEE
EEMNEeMENEMTET
ENNNmNENEEEEEE
ETEeNEELLENLEE
LLnELTNEMLLEEE
EtTELLEENMEMNE

```

Good luck: ABRACADABRA - 22:

```
DRADCBBAAAABABABARBCCB
DBCABAAADABACDBAAAARBA
CDABBDRBRRBDARRDCRARRA
BAAAACRABRACBARAAABBRC
ACARDARARAAAABRABAADBB
BBAAAARBCDRAACDAADARAB
ABBAAAARABBBAAABACDAAA
AADARDARAAARABRCBABRBB
ARRADCCDACRAAAAAADBAAC
AAAABBARDBAARRCABRDDAA
RADABRAAARAABRRAARDARB
AARARCRBAACARBABRDDDAA
BABACDCCARCRAAADCABARA
RBABACAAAAAACDARRBCACR
RARABBADRARBCRAABRDRAR
BBRAAAAABRBAAABRAACRAR
BAADRAAAABRDAAABBBBAAA
RAADRACDAADABRACAAABRR
AARAAABBAAABRAABCCBAAR
RAAAAAARBRRBARAAAAAARR
RCAAAAARARBRCCBBCCACAA
DAAAABARDABADRAADAAACC

```

> If you run this in the snippet, and look at the console, the last number will show the coords of the beginning of the answer.

Extra: MISSISSIPPI - 32:

```
SPSSIIPSMIMIMPMISPPIIPSIIIIISSSS
ISISIISSMPPPISSIISPPPSPSISSSIPMP
PSPMIIMISMISSIPMPIIIIISIMIMSSSSI
PSIISPSIPSPSIPIPMMMIPIISSMMISMMM
SPIISIPMSISPMPPPMIMPIISISIIISIPS
ISSIISMISSPMIPPISSSMSIISIISSMIPS
SSPISIMSSSIPSSSPMSSPISPPSSSSPSSM
IPMIISMISSSSSSSSSPSMPISISIMIISSP
IISSSSMMPSPSISIIISISSMMSISIMPSPP
IIIIIIMIISISMPPPIIISSMSSIPSSSISI
IPIIPPSSSSIISIISSMIPIISSPPSSIPIS
PSISPIIISPPSIIMPIIPSSSSSISPIISSS
SIISSIMSIISSISSSSMIISSIPSIIIIIII
MPSSISSSISISSPMPSISSISSSSISIIMII
ISPSIIIPIIIISMSSMIIPMSSSPSSSSSSS
SSIIIISPIIPIPISIPSMPPMSSSISIIIPI
IPPIPMPIPSIIPPISSPISPSPIIIISIIMS
SPMSSPIIPPSSISISIPSSPSIIISIIIPIP
PSSIIIISMSSIIIMSSIIIPSMPMSIPIIIM
IISSSIIMIMPMISPPIPMMMIIIPSPPSPIS
SISISSIISISSISPSSSSPSIIISIPPISSI
IMSIPSISIIMPSSSISISIISIPSSSSISII
PMIPPPSSISIIISSSSSIIIPISSISIPSMI
ISIPSMMMSMISPISIPSSPSSPISSISIIIS
SISMIIISSIIMSIPMSSSSIPSSSPISPSPI
PPSPISSSISPSIIISSSSPIPSSMIPSSSPS
SSIMSSIISIIPSPSIPSSMSIIIMSSSIPPP
PMSISSPMISIIISIIPSPSPSMSIMISIMIP
IPSISSIIPSSPIMSSSSSSSSSSIIIPISSI
PSIIMIMIISPSSIMISMMPPIPPSSMISMII
IPPIPSIISSSSIPIIPIMMISSIPISIIIIP
IPPISSIMSIIPPSISIISSSMIIIPSIISSS

```

> Try to find MISSISSIPPI! I will comment the answer later. No cheating.
> 4 votes

# Answer
# C++

I wrote this one up today. It is not the most efficient way and does not always generate the most random looking word searches but it gets the job done and it does it relatively quick.

**Bonus:** Supports Palindromes too!!!

It works by taking input for the word and the size of the word search. It then generates infurators by dropping letters, inserting letters, or flipping letters. It then adds those to the grid as well as the correct word. It then checks all instances of the first letter in every direction for the word. If 1 instance is not found ( 2 for palindromes ) it brute forces the cycle over. It then outputs the word search to console as well as a file.

Here it is at 213 lines of code with whitespace and comments.

```
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include <stdio.h>
#include <time.h>

// Keep Track of Coordinates
struct XY {

public:
    int X;
    int Y;
};

// Just in case someone breaks the rules
std::string ToUppercase( const std::string& pWord ) {
    char *myArray = new char[ pWord.size() + 1 ];
    myArray[ pWord.size() ] = 0;
    memcpy( myArray, pWord.c_str(), pWord.size() );

    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        if ( (int) myArray[ i ] >= 97 && (int) myArray[ i ] <= 122 ) {
            myArray[ i ] = (char) ( (int) myArray[ i ] - 32 );
        }
    }

    return std::string( myArray );
}

// Random number between a max and min inclusively
int RandomBetween( int pMin, int pMax ) {
    return rand() % ( pMax - pMin + 1 ) + pMin;
}

// Find all instances of a character
std::vector<XY> FindHotspots( const std::vector<char> &pWordSearch, char pFirstChar, unsigned int pLength ) {
    std::vector<XY> myPoints;
    for ( unsigned int i = 0; i < pLength; i++ ) {
        for ( unsigned int j = 0; j < pLength; j++ ) {
            if ( pWordSearch[ i * pLength + j ] == pFirstChar ) {
                XY myXY;
                myXY.X = i;
                myXY.Y = j;
                myPoints.push_back( myXY );
            }
        }
    }
    return myPoints;
}

// Searchs each index from specific point in certain direction for word
// True if word is found
bool Found( const std::vector<char> &pWordSearch, const std::string &pWord, int pRow, int pCol, int pX, int pY, int pLength ) {
    for ( unsigned int i = 0; i < pWord.length(); i++ ) {
        if ( pRow < 0 || pCol < 0 || pRow > pLength - 1 || pCol > pLength - 1 )
            return false;
        if ( pWord[ i ] != pWordSearch[ pRow * pLength + pCol ] )
            return false;
        pRow += pX;
        pCol += pY;
    }
    return true;
}

// Goes through all the hotspots and searchs all 8 directions for the word
int FindSolution( const std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
    std::vector<XY> myHotspots = FindHotspots( pWordSearch, pWord[ 0 ], pLength );

    int mySolutions = 0;
    for ( unsigned int i = 0; i < myHotspots.size(); i++ ) {
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 0, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 0, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, -1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, -1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, -1, pLength ) )
            mySolutions++;
    }
    return mySolutions;
}

// Generate words that are similar
//
// 1. Word with last character same as first
// 2. Word with 1 character removed
// 3. Word with 1 character added
std::vector<std::string> GenerateInfurators( const std::string &pWord ) {
    std::vector<std::string> myInfurators;
    for ( unsigned int i = 0; i < pWord.size() / 2; i++ ) {
        char myReplace = '0';
        do {
            myReplace = pWord[ RandomBetween( 0, pWord.size() - 1 ) ];
        } while ( myReplace == pWord[ pWord.size() - 1 ] );
        myInfurators.push_back( pWord.substr( 0, pWord.size() - 2 ) + myReplace );
    }

    for ( unsigned int i = 1; i < pWord.size() - 2; i++ ) {
        myInfurators.push_back( pWord.substr( 0, i ) + pWord.substr( i + 1 ) );

        std::string myWord = pWord;
        myInfurators.push_back( myWord.insert( i, 1, pWord[ i - 1 ] ) );
    }

    return myInfurators;
}

// Adds word in random position in word search
void AddWordRandomly( std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
    int myXDirec = 0;
    int myYDirec = 0;
    do {
        myXDirec = RandomBetween( -1, 1 );
        myYDirec = RandomBetween( -1, 1 );
    } while ( myXDirec == 0 && myYDirec == 0 );

    int myRow = 0;
    if ( myXDirec == 0 ) {
        myRow = RandomBetween( 0, pLength - 1 );
    } else if ( myXDirec > 0 ) {
        myRow = RandomBetween( 0, pLength - pWord.size() - 1 );
    } else {
        myRow = RandomBetween( pWord.size(), pLength - 1 );
    }

    int myCol = 0;
    if ( myYDirec == 0 ) {
        myCol = RandomBetween( 0, pLength - 1 );
    } else if ( myYDirec > 0 ) {
        myCol = RandomBetween( 0, pLength - pWord.size() - 1 );
    } else {
        myCol = RandomBetween( pWord.size(), pLength - 1 );
    }

    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        pWordSearch[ myRow * pLength + myCol ] = pWord[ i ];
        myRow += myXDirec;
        myCol += myYDirec;
    }
}

// Checks for palindromes
bool WordIsPalindrome( const std::string &pWord ) {
    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        if ( pWord[ i ] != pWord[ pWord.size() - 1 - i ] )
            return false;
    }
    return true;
}

int main() {
    // Handle all input
    std::string myWord;
    std::cin >> myWord;
    myWord = ToUppercase( myWord );

    std::string myStrLength;
    std::cin >> myStrLength;
    unsigned int mySideLength = std::stoi( myStrLength );

    // Setup variables
    // New time seed
    // Generate infurators
    // Add words
    std::vector<char> myWordSearch;
    srand( ( unsigned int ) time( 0 ) );
    std::vector<std::string> myWords = GenerateInfurators( myWord );
    myWords.push_back( myWord );

    bool myWordIsPalindrome = WordIsPalindrome( myWord );

    // Brute force words until 1 instance only
    // 2 instances for palindromes
    do {
        for ( unsigned int i = 0; i < mySideLength * mySideLength; i++ ) {
            myWordSearch.push_back( myWord[ RandomBetween( 0, myWord.size() -1 ) ] );
        }

        for ( unsigned int j = 0; j < 10; j++ ) {
            for ( unsigned int i = 0; i < myWords.size() - 1; i++ ) {
                AddWordRandomly( myWordSearch, myWords[ i ], mySideLength );
            }
        }
        AddWordRandomly( myWordSearch, myWord, mySideLength );
    } while ( ( FindSolution( myWordSearch, myWord, mySideLength ) != 1 && !myWordIsPalindrome ) ||
            ( FindSolution( myWordSearch, myWord, mySideLength ) != 2 && myWordIsPalindrome ) );

    // Output to console && text file
    std::ofstream myFile( "word_search.txt" );
    for ( unsigned int i = 0; i < mySideLength; i++ ) {
        for ( unsigned int j = 0; j < mySideLength; j++ ) {
            myFile << myWordSearch[ i * mySideLength + j ] << "";
            std::cout << myWordSearch[ i * mySideLength + j ] << " ";
        }
        myFile << "\n";
        std::cout << "\n" << std::endl;
    }
    myFile.close();

    system( "pause" );
    return 0;
}

```

I am far from a C++ expert so I'm sure there's places where this code could be improved but I was happy with how it ended up.

Here's the outputs.

```
BANANA-12:
BBBBBABANABB
BBANAAANANBB
BABAANABBABA
BNAANAAANABN
BANNNNNANBBB
AANABNNANNAA
NAANANAAAABA
ANNNBAANNNBN
ABABNAANABNA
BNNANNAAANNB
BBABAAANBBAB
BBANANNBBABB

ELEMENT-14:
MLELEMEEETNEET
EMTTELTEETELEE
EMNNELEENLNTEL
TLTNEEMEEELMTM
TLEMLNLMEEEETE
TTEEEEEENLNTLE
NETNENEEMTTMEN
ELELTETEEMNMEE
MTEEMTNEEEENEM
ELENEEEMMENNME
ELLEELELTMLETL
ETLTNEMEEELELE
EELTLLLLLMNEEE
EEEELEMNTLEEEE

ABRACADABRA-22:
ACRABAACADABBADBRRAAAA
BBABAABAARBAAAARBAABAA
RARRARBAAABRRRRAAABBRA
DABARRARABBBBABABARABR
BRBACABBAAAABAARRABDAD
ABRRCBDADRARABAACABACR
DCAAARAABCABRCAAAARAAA
AAABACCDCCRACCDARBADBA
CAARAAAAAACAAABBAACARA
ADRABCDBCARBRRRDAABAAR
RARBADAARRAADADAABAAAB
BBRRABAABAAADACACRBRAA
ARBBBDBRADCACCACARBABD
CAARARAAAACACCDARARAAA
ARABADACRARCDADABADBBA
RARAADRRABADBADAABBAAA
RAAAABBBARRDCAAAAAARRA
BABBAAACRDBABCABBBRAAR
AARARAARABRAAARBRRRAAB
BAAAARBRARARACAARAAAAA
ADCBBABRBCBDBRARAARBAA
AARBADAAAARACADABRAABB

Bonus: RACECAR-14:
RRACEARCECARAR
RRRRRRRRRCARAR
RARRAACECARAAA
CCACECRREAECAR
RECEAEEAAECEAE
RCRRREACCCCEAR
RRRARCERREERRR
CCARAAAAECCARC
ECECARRCCECCRR
CARRRACECCARAC
ACRACCAAACCCAR
ARRECRARRAAERR
RRCRACECARRCRR
RRRRACECRARRRR

```

I may update this to generate slightly more "random" looking word searches.
> 3 votes

# Answer
### Excel VBA

```
Dim l() As String
w = InputBox("w")
n = InputBox("n")
ReDim l(Len(w))
Var = w
q = Len(w)
For i = 1 To Len(w)
l(i) = Left(Var, 1)
Var = Right(Var, Len(w) - i)
Next i
Cells(Int((q) * Rnd + 1), Int(((n - q) * Rnd + 1))).Select
r = Int((3) * Rnd + 1)
If r = 1 Then
For i = 0 To q - 1
ActiveCell.Offset(0, i) = l(i + 1)
Next
ElseIf r = 2 Then
For i = 0 To q - 1
ActiveCell.Offset(i, 0) = l(i + 1)
Next
ElseIf r = 3 Then
For i = 0 To q - 1
ActiveCell.Offset(i, i) = l(i + 1)
Next
End If
For i = 1 To n
For j = 1 To n
If Cells(i, j) = "" Then
Cells(i, j) = l(Int((q - 1) * Rnd + 1))
End If
Next j
Next i

```

It works by first randomly placing the word in the spread sheet, random in both position and direction, then filling the non-empty spaces in the surrounding grid by randomly choosing from all but the last letter of the word.

BANANA Output (2, 1):

```
N   B   N   A   N   A   N   N   A   B   B   A
A   A   N   A   A   A   B   A   N   A   A   N
N   N   A   B   A   N   B   N   B   A   N   N
B   A   B   N   A   N   N   A   N   A   B   N
N   N   A   N   A   N   N   A   A   A   A   B
A   A   B   A   N   N   A   B   A   N   A   A
A   A   A   A   A   N   A   N   A   A   N   A
A   N   A   B   B   A   N   A   N   B   N   N
A   A   N   N   A   B   A   N   A   B   N   A
A   N   A   N   A   N   B   A   B   N   A   A
A   N   A   A   B   A   B   N   N   N   B   A
B   A   A   A   N   N   N   A   B   N   A   A

```

ELEMENT Output (6, 5):

```
E   E   L   M   M   M   L   E   E   N   M   M   E   E
E   E   M   E   L   E   E   M   E   E   E   E   E   L
E   N   E   E   E   E   E   L   E   N   E   E   E   E
L   E   M   M   M   E   E   L   E   L   N   L   M   E
E   L   L   L   E   E   M   L   E   M   M   E   E   E
L   E   M   L   N   N   L   M   E   E   L   E   M   N
L   L   N   E   M   M   M   E   E   N   E   E   E   L
E   E   N   E   N   L   E   N   M   L   N   N   N   M
M   E   E   M   M   N   E   E   M   E   E   E   E   L
N   E   M   M   M   E   E   L   N   L   N   E   L   E
L   M   E   L   M   M   N   N   L   E   E   T   E   M
E   E   E   N   L   M   E   E   M   E   E   E   E   E
M   E   E   E   E   L   N   M   L   E   E   E   E   E
N   L   L   M   E   M   E   L   E   M   E   M   N   E

```

ABRACADABRA Output (2, 3):

```
R   B   A   R   A   R   D   R   D   A   A   R   R   D   R   A   A   C   A   R   B   A
C   B   B   R   R   A   A   A   R   A   B   A   C   R   A   A   A   D   D   A   C   A
B   A   B   R   A   C   A   D   A   B   R   A   R   A   A   R   D   B   B   B   C   R
C   R   C   A   A   R   B   D   R   A   A   A   R   A   R   D   D   B   R   B   D   A
C   A   D   A   C   A   A   D   B   A   R   D   A   A   D   D   B   D   R   A   R   B
A   A   R   R   R   B   R   B   R   B   A   A   R   C   R   B   C   A   A   A   A   A
A   R   A   B   R   A   R   A   C   D   R   A   A   R   C   A   D   C   B   C   C   D
D   R   A   A   A   D   B   C   C   R   A   A   R   B   B   A   B   A   R   B   C   R
A   R   B   R   R   C   D   R   R   B   D   A   B   A   C   C   B   A   A   A   R   R
A   A   D   A   A   A   B   D   R   A   B   A   R   A   D   B   A   A   B   B   D   R
C   A   A   B   R   R   B   A   B   B   R   A   A   C   A   D   A   R   A   A   A   A
A   R   R   C   R   R   A   R   C   A   B   A   A   A   R   A   A   R   A   R   C   R
D   B   C   A   B   A   A   A   A   B   C   A   B   B   D   A   R   R   B   B   R   A
B   A   C   B   B   D   C   B   D   B   A   A   A   A   D   A   R   R   C   C   A   R
A   A   R   R   R   R   D   A   R   C   A   A   B   A   B   C   C   A   A   R   A   R
C   A   B   A   B   R   B   C   B   B   C   B   D   A   A   R   A   R   A   B   D   D
R   A   A   A   C   B   R   D   R   B   B   R   A   R   C   D   A   A   C   A   D   A
A   D   B   A   C   R   A   C   B   A   R   A   A   A   A   C   A   R   D   A   D   B
A   R   B   B   A   A   R   A   B   A   R   A   A   R   A   R   B   R   D   B   D   A
R   B   D   B   B   A   B   R   C   D   A   C   A   A   R   C   B   A   B   B   D   R
B   C   B   A   B   A   B   D   D   B   B   R   B   B   B   A   A   R   R   A   A   C
R   D   A   C   A   A   A   R   C   R   R   A   C   R   C   A   B   R   B   A   R   A

```
> 0 votes

---
Tags: code-challenge, word-search
---


title: Rocket Bots KOTH

text:
# Question
Title: Rocket Bots KOTH
## Rocket Bots

The year is 3024. People have become too scarce a resource to risk in war, so combat has shifted to the robots. Your task is to construct a bot like no other, who's rockets will rain destruction down on your foes and shoot down all incoming threats.

## Gameplay

### Bots

Gameplay takes place on a 10x15 grid. Your bot is located off the bottom edge, and has three slots at spots 6,7 and 8 of the grid. Your opponent is located at the top of the grid, with three slots directly opposite yours.

### Rockets

From any of these slots, you can fire a rocket, assuming the slot has not been destroyed. A rocket consists of a list of directions that is given to it when created, and once fired these directions cannot be changed. Each turn, the rocket will consume the top of the list, and move in that direction. Rockets move simultaneously. If two rockets end in the same tile, they will both explode. If a rocket runs out of commands, it will explode. If a rocket runs out of fuel, after 100 moves, it will explode. When a rocket explodes, it will remain in that tile for 5 turns, causing any other rockets that move there to explode as well.

*Note:* Because of the simultaneous movement, two rockets can pass each other without exploding, as long as they do not both end a turn in the same tile.

### Goal

The goal of each match is to destroy your opponents slots while keeping yours alive. A rocket can be fired from any live slot you have, and is given a path designated by you before it is fired. **You fire a rocket every second turn, meaning rockets will move twice before you can fire another one.** A duel lasts for 200 turns, or until one bots slots are all destroyed.

### Scoring

At the end of the match, you get one point for each live slot you have, and one point for each opponents slot you destroyed. This means it is a zero-sum game, and 6 points will be awarded each match.

A round robin will be run so that each bot faces each other bot once. If any bots use RNGs, then each matchup will be 1000 duels instead.

## Implementation

Code for the competition can be found here: https://github.com/Cain93/RocketBots

Each submission should extend the `Bot` class. You must override the `fireRocket` method. This method receives a grid array of Rockets, `Rocket[][]`, that represents the gameboard. You are always located at the bottom of the grid, with slots at spots `[-1][6]`, `[-1][7]`, `[-1][8]`. On the grid, unoccupied spots will be represented with `null`. If a rocket exists in a tile, you can identify who it belongs to by accessing the `dis` field. "^" is your rocket, and "v" is your opponents.

You must return a LinkedList of Integers that gives the instructions for your rocket. To move up, use 0. To move up and right, use 1, just right, use 2, etc all the way to 7 for up and left. The rocket will move in the order you push Integers. For example, the following code will make the rocket move upwards a few turns, zig-zag a few turns and then detonate.

```
LinkedList<Integer> moves = new LinkedList<Integer>();

moves.push(0);
moves.push(0);
moves.push(0);
moves.push(1);
moves.push(7);
moves.push(1);
moves.push(7);

```

To change which slot to fire the rocket from, change the `curSlot` field. 0 is your leftmost slot, and 2 is your rightmost. To check if a slot is destroyed, use `getSlot(int slotNumber)`.

If a rocket ends a turn on a slot, that slot will be destroyed. You do not need to manually detonate the rocket.

*Note:* Rockets spawn at the location of the slot fired from, but will move once before collisions are evaluated. So if you fire a rocket from slot 0, and the first move is right (2), then you will destroy your own middle slot. However, up and right (1) is a safe move.

If you want to name your bot, override the `name()` method.

Bots will be re-built for each duel, so any static variables will be reset.

## Good Luck!

May your rockets fly true and your opponents be nothing but smoldering scraps of metal.

Hint:

> Purposefully detonating rockets to create explosions is an easier way to defend than trying to shoot down opponents rockets.

## Example Bot

```
package bots;

import java.util.LinkedList;

import mechanics.*;

public class SimpleBot extends Bot {

    public String name(){
        return "Simple";
    }

    public LinkedList<Integer> fireRocket(Rocket[][] g){

        LinkedList<Integer> l = new LinkedList<Integer>();
        for(int i = 0; i < 12; i++){
            l.push(0);
        }
        return l;
    }

}

```

# Scores

Scores from 6-24

```
Simple: 900
Zigzagoon: 3654
Wall-E: 3606
Tortoise: 2248
3 Shot: 2334
HatTrickBot: 4287
Sniper: 2973
SideShooter: 2491
Terminator: 4835
StraightShot: 3378
Defender: 4570
MoreDakka: 4324

```

# Answer
# Defender

Defender uses a new type of defense: The rockets *are patrolling* in front of the slots. This gives a huge advantage, since rockets live for 100 turns instead of 5 turns (like explosions).

```
package bots;

import java.util.LinkedList;
import mechanics.*;

public class Defender extends Bot {
    int turn = 0;

    @Override
    public String name() {
        return "Defender";
    }

    @Override
    public LinkedList<Integer> fireRocket(Rocket[][] grid) {
        LinkedList<Integer> command = new LinkedList<Integer>();
        for (int i = 0; i < 3; i++) {
            if ((grid[0][6+i] == null || grid[0][6+i].getDis().equals("v")) && (grid[1][6+i] == null || grid[1][6+i].getDis().equals("v")) && getSlot(i)) {
                curSlot = i;
                command.push(0);
                for (int j = 0; j < 50; j++) {
                    command.push(0);
                    command.push(4);
                }
                break;
            }
        }

        if (command.isEmpty()) {
            if ((grid[0][9] == null || grid[0][9].getDis().equals("v")) && (grid[0][10] == null || grid[0][10].getDis().equals("v")) && (grid[1][10] == null || grid[1][10].getDis().equals("v")) && getSlot(2)) {
                curSlot = 2;
                command.push(1);
                command.push(1);
                command.push(4);
                for (int i = 0; i < 50; i++) {
                    command.push(6);
                    command.push(2);
                }
            } else if ((grid[0][5] == null || grid[0][5].getDis().equals("v")) && (grid[0][4] == null || grid[0][4].getDis().equals("v")) && (grid[1][4] == null || grid[1][4].getDis().equals("v")) && getSlot(0)) {
                curSlot = 0;
                command.push(7);
                command.push(7);
                command.push(4);
                for (int i = 0; i < 50; i++) {
                    command.push(2);
                    command.push(6);
                }
            }

        }

        if (command.isEmpty()) {
            if (turn % 2 == 0 && getSlot(0)){
                curSlot = 0;
                command.push(7);
                command.push(7);
                for (int i = 0; i < 7; i++) {
                    command.push(0);
                }
                command.push(2);
                for (int i = 0; i < 2; i++) {
                    if (Math.random() < 0.2) command.push(2);
                }
                command.push(1);
            } else {
                curSlot = 2;
                command.push(1);
                command.push(1);
                for (int i = 0; i < 7; i++) {
                    command.push(0);
                }
                command.push(6);
                for (int i = 0; i < 2; i++) {
                    if (Math.random() < 0.5) command.push(6);
                }
                command.push(7);
            }
        }

        turn++;
        return command;
    }
}

```
> 3 votes

# Answer
# Zigzagoon

The outer slots go (slightly) wide, then head forward and come back in toward the enemy slots. The middle slot shoots a zigzag pattern up the middle.

Every other round (3 turns), it goes into defense mode and just explodes some rockets near my own slots. Attack mode rockets then go around them. Nothing too fancy, just something to get the contest up and running.

```
package bots;import java.util.*;import mechanics.*;

public class Zigzagoon extends Bot{
    String[] evenMoves = {"7000000001","0170710170","1000000007"};
    String[] oddMoves = {"0","00","0"};
    boolean even = true;
    public String name(){return "Zigzagoon";}

    public LinkedList<Integer> fireRocket(Rocket[][] g){
        curSlot = (curSlot+1)%3;
        if(curSlot<1)even=!even;
        String[] moves = even?evenMoves:oddMoves;
        LinkedList<Integer> command = new LinkedList<Integer>();
        for(int i=0;i<moves[curSlot].length();i++)
            command.push(moves[curSlot].charAt(i)-'0');
        return command;
    }
}

```
> 6 votes

# Answer
## Terminator

I'm proud to present Terminator !!!

Each rocket move far left/right from the middle and return on a enemy slot. Every two turns, a defense rocket is launched straight and explode near slot to protect it.

```
package bots;

import java.util.LinkedList;
import mechanics.Bot;
import mechanics.Rocket;

public class Terminator extends Bot {

    int n = 0;
    String[] moves = {"000", "0111107777", "00", "0077700111", "00", "0777701111"};

    public String name() {
        return "Terminator";
    }

    @Override
    public LinkedList<Integer> fireRocket(Rocket[][] g) {
        curSlot = (n+1) % 3;

        LinkedList<Integer> commands = loadCommands(moves[n % moves.length]);
        n++;

        return commands;
    }

    protected LinkedList<Integer> loadCommands(String commands) {
        LinkedList<Integer> linkedList = new LinkedList<Integer>();

        for (int i = 0; i < commands.length(); i++) {
            linkedList.push(commands.charAt(i) - 48);
        }

        return linkedList;
    }

}

```
> 5 votes

# Answer
# HatTrickBot

I had DoubleTapBot for CodeBot 3, who was hitting twice on a turn, here comes HatTrickBot : Hitting all the 3 spots at the same time !

It is always possible to prevent a rocket to hit if you know where it will fall. But I don't think there's many bot that will be able to protect their slots against a 3 rocket attack.

By the way, yes, it's horrible to see such elseif with repeated switch. I could have created a var to switch on with unique values for each combination of the status of slots and the turnConter. But it would be harder to read (I would have to keep the meaning of the values in a comment... boring !) :)

```
package bots;
import java.util.LinkedList;
import mechanics.*;
/*
 * HatTrickBot always tries to destroy all the enemy slots at once
 * In order to achieve this, each slot needs extrem concentration and coordination
 * It explain why they need some turns to re-synchronized the rockets after one of them dies.
 */
public class HatTrickBot extends Bot
{
    // Default moves are at [0]
    // moves at [1] are used when there's only 2 slots remaining
    // moves  [2-4] are here for when there's only 1 slot remaining
    // it panicks, and can't establish how to fire to do a hat trick.
    // So he will just spamm every ennemy position, one at a time
    String[] rightSlot = {  "770002000020",
                            "0000000001",
                            "0000000000",
                            "0000000001",
                            "0000000011"};
    String[] midSlot   = {  "0000000000",
                            "11000060000",
                            "0000000000",
                            "0000000010",
                            "0000000700"};
    String[] leftSlot  = {  "11000060007",
                            "777702000020",
                            "0000000000",
                            "0000007000",
                            "0000077000"};
    int turnCounter=-1;
    public String name(){return "HatTrickBot";}
    public LinkedList<Integer> fireRocket(Rocket[][] g)
    {
        turnCounter=(turnCounter+1)%3;
        String[][] moves = {rightSlot,midSlot,leftSlot};
        LinkedList<Integer> ll = new LinkedList<Integer>();
        boolean slotL=getSlot(0),slotM=getSlot(1),slotR=getSlot(2);
        int movePoint=0;
        if(slotL&&slotM&&slotR)
        {
            switch(turnCounter)
            {
            case 0: curSlot=0;
                break;
            case 1: curSlot=2;
                break;
            case 2: curSlot=1;
                break;
                default:break;
            }
            movePoint=0;

        }
        else if(!slotM&&slotL&&slotR)
        {
            switch(turnCounter)
            {
            case 0: curSlot=0;
                    movePoint=0;
                break;
            case 1: curSlot=2;
                    movePoint=0;
                break;
            case 2: curSlot=0;
                    movePoint=1;
                break;
                default:break;
            }
        }
        else if(!slotL&&slotM&&slotR)
        {
            switch(turnCounter)
            {
            case 0: curSlot=0;
                    movePoint=0;
                break;
            case 1: curSlot=1;
                    movePoint=1;
                break;
            case 2: curSlot=0;
                    movePoint=1;
                break;
                default:break;
            }
        }
        else if(!slotR&&slotM&&slotL)
        {

            switch(turnCounter)
            {
            case 0: curSlot=2;
                    movePoint=1;
                break;
            case 1: curSlot=1;
                    movePoint=1;
                break;
            case 2: curSlot=1;
                    movePoint=0;
                break;
                default:break;
            }
        }
        else
        {
            if(slotR)curSlot=0;
            if(slotM)curSlot=1;
            if(slotL)curSlot=2;
            movePoint = 2+turnCounter;
        }
        for(int i=0;i<moves[curSlot][movePoint].length();i++)
            ll.push(Integer.parseInt(moves[curSlot][movePoint].charAt(i)+""));
        return ll;
    }
}

```
> 3 votes

# Answer
# SideShooter

First shoots via the first ( rightmost ) turret in one of two different ways. Then, it shoots via the last ( leftmost ) turret in one of two different ways. Then it makes a "wall" with the second ( middle ) turret by exploding rockets in front of each turret. This process is repeated.

If the game lasts for more than 30 turns, SideShooter grows bored and changes in a small way. Instead of making a "wall" with the second ( middle ) turret, it shoots straight. The rest of the turrets behave the same way.

```
import java.util.LinkedList;

public class SideShooter extends Bot {

    int[] launcher = new int[]{1, 3, 2, 2, 2};
    String[] right = {"1100000077", "100000007"};
    String[] left  = {"7700000011", "700000001"};
    int position = -1;
    int turns = 0;

    public String name(){
        return "SideShooter";
    }

    public LinkedList<Integer> fireRocket(Rocket[][] g){
      LinkedList<Integer> directions = new LinkedList<Integer>();

      if(getSlot(0) || getSlot(1) || getSlot(2))
          do{
              position = (position + 1) % 5;
              curSlot = launcher[position] - 1;
          }while(!getSlot(curSlot));

      if(position == 0)
      {
          String shoot = left[((int) (Math.random() * left.length))];
          for(int i=0; i < shoot.length(); i++)
              directions.push(shoot.charAt(i)-'0');
      }else if(position == 1)
      {
          String shoot = right[((int) (Math.random() * right.length))];
          for(int i=0; i < shoot.length(); i++)
              directions.push(shoot.charAt(i)-'0');
      }else
      {
          if(turns < 30)
          {
            if(position == 2 )
                directions.push(0);
            else if(position == 3)
                directions.push(1);
            else if(position == 4)
                directions.push(7);
          }else
              for(int i=0; i < 10; i++)
                  directions.push(0);
      }
      turns ++;
      return directions;
    }

}

```
> 2 votes

# Answer
# Sniper

Sniper first blocks its two sides and then starts shooting straight.

```
import java.util.LinkedList;

public class Sniper extends Bot {

    int[] launcher = new int[]{1, 3, 1, 2, 3};
    String[] moves = {"7", "1", "0000000000", "0000000000", "0000000000"};
    int position = -1, move = 0;

    public String name(){
        return "Sniper";
    }

    public LinkedList<Integer> fireRocket(Rocket[][] g){
        LinkedList<Integer> directions = new LinkedList<Integer>();

        if(getSlot(0) || getSlot(1) || getSlot(2))
        do{
            position = (position + 1) % launcher.length;
            curSlot = launcher[position] - 1;
        }while(!getSlot(curSlot));

        for(int i=0; i < moves[move].length(); i++)
            directions.push(moves[move].charAt(i)-'0');

        move = (move + 1) % moves.length;

        return directions;
    }

}

```
> 2 votes

# Answer
# Tortoise

If I protect all my bases, I have 3 points. Bases can only be attacked from 5 locations if I get the grid well. Rocket lasts 5 turn on the field...

This bot uses all of this to match its goal : surviving with at least 50% of the points in the pocket. It shoots 3 rockets, then cover itself

```
package bots;

import java.util.LinkedList;

public class Tortoise extends Bot
{
    int turnCounter=-1;
    boolean attacked=false;
    int[] moves={7,0,0,0,1};
    public String name(){return "Tortoise";}
    public LinkedList<Integer> fireRocket(Rocket[][] g)
    {
         LinkedList<Integer> rocket = new LinkedList<Integer>();
         turnCounter++;
         if(!attacked)
         {
             curSlot=turnCounter;
             for(int i=0;i<11;i++)
                 rocket.push(0);
             if(turnCounter==2)
                 attacked=true;
             return rocket;
         }
         turnCounter%=5;
         switch(turnCounter)
         {
         case 0:
         case 1:curSlot=0;break;
         case 2:curSlot=1;break;
         case 3:
         case 4:curSlot=2;break;
            default:break;
         }
         rocket.push(moves[turnCounter]);
         return rocket;
    }
}

```
> 2 votes

# Answer
# Three Shot

We got some weird shots flying. No true defense, but the pattern is such that it will be hard to get a shot past this bizarre hail of missiles. (or that is the idea. it most likely will not work.)

```
package bots;import java.util.*;import mechanics.*;

public class ThreeShot extends Bot{
    public String name(){state = 0;return "3 Shot";}
    private int state;

    public LinkedList<Integer> fireRocket(Rocket[][] g){
        LinkedList<Integer> command = new LinkedList<Integer>();
        if(state < 2){
           state++;
           return fireLeft();
        }
        if(state < 4){
           state++;
           return fireCenter();
        }
        state=(state+1)%6;
        return fireRight();
    }
    LinkedList<Integer> fireCenter(){
        LinkedList<Integer> command = new LinkedList<Integer>();
        curSlot = 1;
        while(command.size()<90){
            command.push(1);
            command.push(7);
            command.push(6);
            command.push(1);
        }
        return command;
    }
    LinkedList<Integer> fireRight(){
        LinkedList<Integer> command = new LinkedList<Integer>();
        curSlot = 2;
        command.push(1);
        for(int i=0;i<8;i++){
            command.push(0);
        }
        command.push(7);
        return command;
    }
    LinkedList<Integer> fireLeft(){
        LinkedList<Integer> command = new LinkedList<Integer>();
        curSlot = 0;
        command.push(7);
        for(int i=0;i<8;i++){
            command.push(6);
            command.push(1);
        }
        command.push(1);
        return command;
    }
}

```

Note
> 2 votes

# Answer
# MoreDakka

MoreDakka shoots in five directions without a stop (until turrets gets wrecked by other missiles).

```
import java.util.LinkedList;

public class MoreDakka extends Bot
{
    String[] moves={"70000000001", "0000000000", "0000000000", "0000000000", "1000000007"};
    int[] launcher = new int[]{0, 0, 1, 2, 2};
    int position = -1;

    public String name(){
        return "MoreDakka";
    }

    public LinkedList<Integer> fireRocket(Rocket[][] g)
    {
         LinkedList<Integer> directions = new LinkedList<Integer>();

         if(getSlot(0) || getSlot(1) || getSlot(2))
            do{
                position = (position + 1) % launcher.length;
                curSlot = launcher[position];
            }while(!getSlot(curSlot));

         for(int i=0; i < moves[position].length(); i++)
            directions.push(moves[position].charAt(i)-'0');

         return directions;
    }
}

```
> 2 votes

# Answer
# StraightShot

Just fire right at them.

```
package bots;import java.util.*;import mechanics.*;

public class StraightShot extends Bot{
    public String name(){return "StraightShot";}

    public LinkedList<Integer> fireRocket(Rocket[][] g){
        LinkedList<Integer> command = new LinkedList<Integer>();
        curSlot = (curSlot+1)%3;
        for(int i=0;i<100;i++)
            command.push(0);
        return command;
    }
}

```
> 1 votes

# Answer
Here's my own entry

# WallE

Shoots some offset rockets, and builds walls on his edges and center. After 100 turns, starts targeting the middle slot.

```
package bots;

import java.util.LinkedList;
import java.util.Random;

import mechanics.*;

public class WallE extends Bot {

    int turn = 2;

    public String name(){
        return "Wall-E";
    }

    public LinkedList<Integer> fireRocket(Rocket[][] g){
        turn++;
        LinkedList<Integer> moves = new LinkedList<Integer>();
        curSlot = 1;
        switch(turn%4){
        case 0:
            //Check the right wall
            if(getSlot(2)){
                curSlot = 2;
                moves.push(1);
                return moves;
            }
        case 1:
            //Check the left wall
            if(getSlot(0)){
                curSlot = 0;
                moves.push(7);
                return moves;
            }
        case 2:
            //Check the center wall
            if(getSlot(1)){
                curSlot = 1;
                moves.push(0);
                return moves;
            }
            break;
        default:
            //Fire a sneaky rocket
            Random rand = new Random();
            int direction = rand.nextInt(2);
            int back = 0;
            if(direction == 0 && getSlot(2)){ direction = 1; back = 7; curSlot = 2;}
            else{ direction = 7; back = 1; curSlot = 0; }
            moves.push(0);
            moves.push(direction);
            moves.push(direction);
            for(int i = 0; i < 5; i++){
                moves.push(0);
            }

            //Go for the center after turn 100
            if(turn > 104){
                moves.pop();
                moves.push(back);
            }
            moves.push(back);
            moves.push(back);

        }

        return moves;

    }

}

```
> 1 votes

---
Tags: king-of-the-hill, java
---


title: Analyzing Earthquakes

text:
# Question
Title: Analyzing Earthquakes
# Background

The Random Domino Automaton is a toy model for earthquakes, inspired by cellular automata. In this challenge, your task is to simulate a simplified version of this model, and collect data out of it.

The automaton is defined on an array `A` of `k` bits, representing a fault line on which earthquakes may occur. The array wraps around at its borders. The condition `A[i] = 0` means that position `i` is *relaxed*, and `A[i] = 1` means that it's *excited*, or contains stored energy. At each time step, one position of the array is chosen uniformly at random. If that position is relaxed, it becomes excited (potential energy is added to the system). If that position is already excited, it triggers an earthquake, and the chosen position and all excited positions connected to it are relaxed again. The number of excited positions that become relaxed is the *magnitude* of the earthquake.

# Example

Consider the array

```
100101110111

```

of length 12. If the random process chooses the second bit from the left, the array is updated to

```
110101110111
 ^

```

since the chosen bit (marked with `^`) was `0`. If we next choose the fourth bit from the left, which is an isolated `1`, an eartquake of magnitude 1 is triggered, and the bit is set to `0` again:

```
110001110111
   ^

```

Next, we might choose the second bit from the right, which triggers an earthquake of magnitude 5:

```
000001110000
          ^

```

Note that all `1`s in the same "cluster" as the chosen one were part of the quake, and the array wraps around at the border.

# The Task

You shall take as inputs two positive integers `k` and `t`, and your task is to simulate the random domino automaton for `t` time steps, starting from an initial length-`k` array of all `0`s. Your output shall be a list `L` of `k` integers, where `L[i]` (with 1-based indexing) contains the number of earthquakes of magnitude `i` that occurred during the simulation. You are allowed to drop trailing zeroes from the output.

For the inputs `k = 15` and `t = 1000`, some representative outputs are

```
[117, 97, 45, 26, 10, 5, 3, 1, 3, 0, 0, 0, 0, 0, 0]
[135, 91, 58, 21, 8, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0]
[142, 63, 51, 31, 17, 4, 2, 1, 1, 0, 0, 0, 0, 0, 0]
[106, 75, 45, 30, 16, 8, 5, 2, 2, 0, 0, 0, 0, 0, 0]
[111, 96, 61, 22, 3, 8, 3, 2, 0, 0, 0, 1, 0, 0, 0]

```

# Rules

Both full programs and functions are allowed. The shortest byte count wins, and standard loopholes are disallowed.

Note that you are not required to simulate the automaton using any particular implementation, only the output matters.

# Answer
> 2 votes
# Pyth, 48 bytes

```
Km0QJsM.u?<+vM.sjkZ\1KQe=Z.>NOQ+PZ1vwKm/-VJtJhdQ

```

Got a little bit inspired by @Dennis's explanation. Had some similar thoughts yesterday, but didn't really follow them.

Try it online: Demonstration

### Explanation:

```
      implicit: Q is the first input number
 m0Q  create a list with Q zeros
K     store the list in K

       .u                      vwK   apply the following expression eval(input) times,
                                     start with N = K:
                      .>NOQ            shift N by a random integer of [0, ..., Q-1]
                    =Z                 store the result in Z
     ?             e Z                 if the last digit == 1:
            jkZ                          convert Z to string
          .s   \1                        remove "1"s from the start and end
        vM                               convert to list of integers
       +         K                       add K (adds a bunch of zeros)
      <           Q                      correct size (take the first Q elements)
                                         implicitly update N with this result
                                       else:
                           PZ            all but last of Z
                          +  1           append 1
                                         implicitly update N with this result

   .u                                gives all the intermediate states
 sM                                  sum each list
J                                    store in J

m/-VJtJhdQ
m        Q   map each d in [0, 1, ..., Q-1] to:
  -VJtJ        vectorized minus between J and J[1:]
 /     hd      count d+1 in ^
             implicitly print

```

# Answer
> 5 votes
# CJam, ~~57~~ 55 bytes

```
{:K,K0a*@[{Kmrm<){_{_0#>W%K0e]}2*_)}1?+}*;]1fb2/::-fe=}

```

This is an anonymous function that pops **k** and **t** from the stack (**k** on top of **t**) and leaves the desired array in return.

Try it online in the CJam interpreter.

### How it works

```
:K         e# Save the topmost integer (k) in K.
,          e# Push I := [0 ... K-1].
K0a*       e# Push J := [0 ... 0] (K elements).
@          e# Rotate the other integer (t) on top of the stack.
[{         e# Do t times:
  Kmr      e#   Pseudo-randomly select an integer between 0 and t-1.
  m<       e#   Rotate the array J than many units to the left.
  )        e#   Pop out the last element.
  {        e#   If it is 1:
    _      e#     Copy J.
    {      e#     Do 2 times:
      _0#  e#       Push the first index of 0 in J.
      >    e#       Discard the preceding elements.
      W%   e#       Reverse the array.
      K0e] e#       Pad it with zeroes to length K.
    }2*    e#
    _)     e#     Copy J and pop out the last element.
  }        e#
  1?       e#   Else: Push 1.
  +        e#   Push the integer on the stack on J.
}*         e#
;          e# Discard the last value of J.
]          e# Collect the intermediate values of J in an array.
1fb        e# Replace each array by the sum of its elements (number of ones).
2/         e# Split the array into chunks of length 2.
::-        e# Replace each chunk by the difference of its elements.
fe=        e# Count the occurrences of each integer in I.

```

# Answer
> 4 votes
# Python 2, ~~174~~ 170

```
from random import*
k,t=input()
D=[0]*k
E=D+[0]
def U(x):b=D[x];D[x]=0;return b and-~U(x-1)+U(-~x%k)
for x in[0]*t:r=randint(0,k-1);e=U(r);E[e-1]+=1;D[r]=e<1
print E[:-1]

```

Thanks @Vioz for finding a shorter way to make `D`, and proving again that `not` is usually golfable. And also for writing the explanation.

I had tried to make a similar program in Pyth, but there seems to be a scope issue in what I was trying to do. This pretty naively implements the dominoes and the function `U` propagates earthquakes. The subtraction direction in `U` doesn't need a mod because it will wrap around naturally. The last element of `E` counts the number of times a zero is turned into a one, so it is not printed at the end.

**Ungolfed + Explanation:**

```
from random import*
k,t=input()                            # Takes input in form k,t
D = [0]*k                              # Empty array of size k is made for
                                       # performing the simulation.
E = D+[0]                              # Empty array of size k+1 is made for
                                       # storing the magnitudes.
def U(x):                              # Define a function U that takes an int x
    b = D[x]                           # Assign b to the value at x in D
    D[x] = 0                           # Clear the value at x in D
    return b and U(x-1)+1 + U((x+1)%k) # Return the sum of U(x-1)+1 and U((x+1)%k)
                                       # if b is a 1.
for x in[0]*t:                         # Perform t tests
    r=randint(0,k-1)                   # Generate a random number between 0 and k-1
    e=U(r)                             # Assign e to the value of U(r)
    E[e-1]+=1;                         # Increment the magnitude array at position
                                       # e-1
    D[r] = e<1                         # Set D[r] to be 1 if no earthquake happened.
print E[:-1]                           # Print the magnitude list

```

# Answer
> 4 votes
# Java, ~~278~~ 272 bytes

Java isn't the best Golf language, and I'm not the best golfer, but it was a lot of fun to write so here it is! Let me know about bugs and improvements! (I decided to resubmit as just a function.)

```
void e(int k, int t){int[]d=new int[k],b=d.clone();for(;t-->0;){int m=0,q=(int)(Math.random()*k),i=q,h=1,f=0;d[q]++;if(d[q]>1){for(;;){if(i<0){i=k-1;h=-1;}if(d[i%k]>0){m++;d[i%k]=0;}else{if(f>0)break;h*=-1;i=q;f=1;}i+=h;}b[m-1]++;}}System.out.println(Arrays.toString(b));}

```

And the file with spaces and comments:

```
void e(int k, int t){
    int[]d=new int[k],b=d.clone();          //b is the record, d is the map

    for(;t-->0;){                           //do time steps //q is the spot
      int m=0,q=(int)(Math.random()*k),i=q,h=1,f=0;
                        //m-magnitude,i spot examining, h moving index, f change counter
      d[q]++;                               //add the energy
      if(d[q]>1){                           //double energy, quake here
        for(;;){                            //shorthand while true
          if(i<0){                          //i has wrapped negative, need to start a left hand search from the end now
            i=k-1;                          //Start at the end
            h=-1;                           //Left handed search
          }
          if(d[i%k]>0){                     //is the spot energetic and set off
           m++;                             //add one to the mag counter
           d[i%k]=0;                        //remove energy
          } else {                          //it's a non active spot so we need to flip search direction
           if(f>0) break;                   //we've already flipped once, break
           h*=-1;                           //flip the direction now
           i=q;                             //reset the spot we look at to the epicenter
           f=1;                             //add one to the flip counter
          }
          i+=h;                             //add the search increment to the spot we look at
        }
        b[m-1]++;                           //update the mag record
      }
    }
    System.out.println(Arrays.toString(b)); //print it out
 }

```

# Answer
> 4 votes
# Python 2, 153 bytes

```
from random import*
k,t=input()
E=[0]*k
L=E+[0]
def g(i,x=0):y=E[i];E[i]=y&x^x;return y and-~g(i-1)+g(-~i%k)
exec"L[g(randrange(k),1)]+=1;"*t
print L[1:]

```

Turns out I had almost the same solution as Fry's, but with a bit more bit fiddling.

# Answer
> 1 votes
# ES6, ~~224~~ ~~196~~ ~~189~~ ~~179~~ 172

The easy stuff has been golfed, but still some work to do. I'll type out an explanation later. Also, if someone can tell me why the short `new Date%k` thing doesn't work so well anymore, that'd be swell.

```
f=(k,t)=>{a=Array(k).fill(0);o=a.slice(0);for(;t--;){c=0;r=Math.random()*k|0;if(a[r]){for(d=r+1;d<k&a[d];c++)a[d++]--;for(d=r-1;d&a[d];c++)a[d--]--;o[c]++};a[r]^=1}return o}

```

Usage is

```
f(10, 1000);

```

# Answer
> 1 votes
# Perl, 212

The previous version I had put up was not correctly wrapping, and implementing that took some work.

```
sub f{sub n{$i=($i+$d)%($#a+1)}($k,$t)=@_;@L=@a=(0)x$k;for(1..$t){$i=$x=int rand($k);if(++$a[$x]>1){$d=1;my%z;for(;;){$z{$i}=1;n;if(!$a[$i]){$d*=-1;n}last if($d>0&&$i==$x)}@z=keys %z;@a[@z]=(0)x@z;++$L[$#z]}}@L}

```

This is probably not the right algorithm for this, but I can't think right now. The ungolfed version is below.

Ungolfed:

```
sub f {
  # n() implements the iterator, so that each time it is called a
  # global index is incremented or decremented correctly wrapping
  # around
  sub n { $i = ($i + $d) % ($#a + 1) }
  # Receive input
  ($k, $t) = @_;
  # Initialise the array for earthquake magnitudes an the fault
  # line
  @L = @a = (0) x $k;

  for(1..$t){
    # Assign a random integer value to two control variables
    # $i is used for moving along the fault, and $x to remember
    # the initial value
    $i = $x = int rand($k);
    # The corresponding value in the fault line is incremented,
    # and earthquakes detected
    if(++$a[$x]>1){
      # Earthquake!
      # To propagate the earthquake, we move along the fault
      # bouncing on unactivated nodes. We stop when we've covered
      # the entire activated block.

      # $d tracks the direction (initially forward);
      $d = 1;
      # %z keeps the indeces of known activated nodes
      my %z;

      for(;;){
        $z{$i} = 1;              # Read current node
        n;                       # Move head
        if (!$a[$i]) {           # If next one is deactivated
          $d *= -1;              # change direction
          n                      # and move the head (bounce!)
        }
        # If we've reached the beginning, and we're moving
        # forward we've covered the entire activated block
        last if ($d > 0 && $i == $x);
      }

      # Deactivate all consecutive activated nodes
      @z = keys %z;
      @a[@z] = (0) x @z;
      # And store the magnitude of the earthquake
      ++$L[$#z];
    }
  }
  # Return list of magnitudes
  @L
}

print join ' ', f(15, 1000), "\n";

```

# Answer
> 1 votes
# CJam, 76 bytes

```
l~_0a*:R@{1$mr_2$={W@@[W1]{{_@0t@)\@K+_2$=}g2$+)}fK;\(_R=)R\t:R;}{1t}?}*;;Rp

```

Well, this is not very competitive. But since it took me long enough, I thought I'd post it anyway.

```
l~     Get input.
_0a*   Initial bit pattern, list of k zeros.
:R     Save away the list of zeros, will be used for histogram.
@{     Pull number of tries to top of stack, and start main loop.
1$mr   Generate random position in range 0 to k-1.
_2$    Duplicate current pattern and position.
=      Get current value of bit at position.
{      Start if statement. This is the block for bit value 1.
W@@    Create initial count of 1 bits in quake, and push it down the stack.
[W1]{  Start for loop over value [-1 1], the two increments for going left/right.
{      Start while loop that proceeds as long as 1 bits are found.
_@0t   Set current value of bit to 0.
@)     Get current bit counter to top of stack, and increment it.
\@     Pull list and bit position back to top of stack.
K+     Increment/decrement bit position.
_2$=   Get value at new bit position.
}g     End of while loop over 1 bits.
2$+)   Restore position to get ready to move in opposite direction.
}fK    End for loop over left/right increment.
;\(_   Pull counter of 1 bits in quake to top of stack.
R=     Get current value in histogram,
)      increment it,
R\t:R  and store it back in the histogram.
;}     End of if branch for 1 bit.
{1t}?  Else branch of if. For 0 bit, simply set it.
}*     End main loop.
;;Rp   Clean up stack and print histogram.

```

Try it online

---
Tags: code-golf, array, random, simulation
---