34
\$\begingroup\$

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.

\$\endgroup\$
  • 17
    \$\begingroup\$ Your infuriators are aptly named. \$\endgroup\$ – Doorknob Jun 13 '15 at 5:35
  • 1
    \$\begingroup\$ I found it! \$\endgroup\$ – DLosc Jun 13 '15 at 6:39
  • 1
    \$\begingroup\$ Something like MURMURS seems like a good test case, since I'd imagine an optimal answer would involve dropping the S \$\endgroup\$ – Sp3000 Jun 13 '15 at 7:16
  • 2
    \$\begingroup\$ My kids love it. Great challenge \$\endgroup\$ – MickyT Jun 13 '15 at 8:00
  • 5
    \$\begingroup\$ @tolos I take it you haven't found banana yet either \$\endgroup\$ – squeamish ossifrage Jun 13 '15 at 10:28
3
\$\begingroup\$

Java Script

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.

\$\endgroup\$
  • 4
    \$\begingroup\$ The second one doesn't contain "ELEMENT" at all. It only contains four T's, and searching backwards reveals that none of the T's lead to proper spellings of ELEMENT. \$\endgroup\$ – Joe Z. Jun 23 '15 at 4:40
  • \$\begingroup\$ Oops, I accidentally pasted used a old version of my code. Facepalm \$\endgroup\$ – Grant Davis Jun 24 '15 at 1:39
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ LOL. I merely glanced at the RACECAR one and found it immediately! \$\endgroup\$ – mbomb007 Jun 17 '15 at 19:30
0
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ I just realised that if the last letter of the word is repeated elsewhere in the word, the word can still be accidentally generated. Will have to re-think this. \$\endgroup\$ – Wightboy Jun 23 '15 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.