Crie um gerador de pesquisa de uma palavra


34

A palavra BANANAaparece exatamente uma vez nesta pesquisa de palavras :

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

A busca da palavra acima contém apenas uma ocorrência da palavra BANANAolhando para cima, baixo, esquerda, direita ou na diagonal, mas tem muitas palavras semelhantes, como BANANB, BANNANA, BNANA, etc.

Seu trabalho é criar um programa que gere pesquisas de palavras irritantes como esta.

Seu programa terá como entrada:

  • Uma palavra, em todas as letras maiúsculas, contendo de três a sete letras únicas, com pelo menos quatro letras no total.

  • Um número, para representar a dimensão da grade quadrada da pesquisa de palavras. O número deve ser pelo menos o número de letras na palavra.

E, em seguida, produza uma pesquisa por palavra usando apenas as letras da palavra, que contém exatamente uma ocorrência da palavra de entrada e o maior número possível de enfurecedores .

Um enfurecedor é definido como uma sequência que tem uma distância Damerau-Levenshtein de uma da palavra de destino e começa com a mesma letra que a palavra. Pois BANANA, isso incluiria palavras como:

  • BANBNA, onde uma das letras foi substituída.

  • BANNANAou BANAANA, onde uma carta extra foi adicionada.

  • BANAN,, BNANAonde uma carta foi excluída, mas não ANANA, pois não há mais a B.

  • BAANNAou BANAAN, onde duas letras consecutivas foram trocadas.

Ao contar os enfurecedores em uma grade de pesquisa de palavras, eles podem se sobrepor, mas você não pode contar uma sequência grande se ela contiver completamente uma sequência menor que você já contou ou vice-versa. (Se você tiver BANANB, não poderá contá-lo novamente se já tiver contado o BANANinverso ou o contrário BNANA.) Você também não pode contar seqüências que contenham completamente ou sejam completamente contidas pela própria palavra de destino (não é possível contar a palavra específica BANANque faz parte BANANA, nem BANANAAou BANANAN.)


Seu programa será testado em uma lista de palavras específica composta pelas palavras que atendem ao requisito da palavra de entrada (a ser fornecida posteriormente depois que eu o gerar), em um tamanho de grade igual ao dobro do comprimento da palavra e será pontuada no número de enfurecedores presentes em cada grade. Por favor, postar seus resultados para as entradas BANANA 12, ELEMENT 14e ABRACADABRA 22para verificação.


17
Seus enfurecedores são apropriadamente nomeados.
Maçaneta


1
Algo como MURMURSparece ser um bom caso de teste, desde que eu imagino uma resposta ideal envolveria deixando cair oS
SP3000

2
Meus filhos adoram. Grande desafio #
MickyT

5
@tolos Eu acho que você também não encontrou banana #
squishish ossifrage

Respostas:


3

Script Java

Bônus: você pode propagar a pesquisa do Word. A semente padrão é: "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

ELEMENTO - 14:

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

Boa sorte: ABRACADABRA - 22:

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

Se você executar isso no trecho e olhar para o console, o último número mostrará as cordas do início da resposta.

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

Tente encontrar MISSISSIPPI! Vou comentar a resposta mais tarde. Sem trapaça.


4
O segundo não contém "ELEMENT". Ele contém apenas quatro T's, e procurar para trás revela que nenhum dos T leva a grafias apropriadas de ELEMENT.
Joe Z.

Ops, colei acidentalmente usei uma versão antiga do meu código. Facepalm
Grant Davis

3

C ++

Eu escrevi este aqui hoje. Não é a maneira mais eficiente e nem sempre gera as pesquisas de palavras com aparência mais aleatória, mas faz o trabalho e o faz relativamente rápido.

Bônus: Também suporta Palindromes !!!

Ele funciona inserindo a palavra e o tamanho da pesquisa por palavra. Em seguida, gera furadores descartando letras, inserindo letras ou invertendo letras. Em seguida, os adiciona à grade e à palavra correta. Em seguida, verifica todas as instâncias da primeira letra em todas as direções da palavra. Se uma instância não for encontrada (2 para palíndromos), a força bruta forçará o ciclo. Em seguida, ele envia a pesquisa de palavras para o console e também para um arquivo.

Aqui estão 213 linhas de código com espaço em branco e comentários.

#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;
}

Como estou longe de ser um especialista em C ++, tenho certeza de que há lugares onde esse código pode ser aprimorado, mas fiquei feliz com a maneira como ele acabou.

Aqui estão as saídas.

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

Posso atualizar isso para gerar pesquisas de palavras com aparência um pouco mais "aleatória".


RI MUITO. Apenas olhei para o RACECAR e o encontrei imediatamente!
Mbomb007 17/06/2015

0

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

Ele funciona primeiro colocando a palavra aleatoriamente na planilha, aleatoriamente na posição e na direção, e depois preenchendo os espaços não vazios na grade circundante, escolhendo aleatoriamente entre a última letra da palavra, exceto a última.

Saída BANANA (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

Saída ELEMENT (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

Saída ABRACADABRA (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

Acabei de perceber que, se a última letra da palavra for repetida em outro lugar, a palavra ainda poderá ser gerada acidentalmente. Terá que repensar isso.
Wightboy
Ao utilizar nosso site, você reconhece que leu e compreendeu nossa Política de Cookies e nossa Política de Privacidade.
Licensed under cc by-sa 3.0 with attribution required.