Vous êtes sur la page 1sur 17

Option Explicit 'Este c�digo intenta solucionar los problemas de 9x9 Su Doku.

'
'Copyright (C) 2004 David Ireland', 'Este programa es software libre, puede
redistribuirlo y / o "modificado bajo los t�rminos de la Licencia P�blica General
de GNU" publicada por la Free Software Foundation, versi�n 2 'de la Licencia, o (a
su elecci�n) cualquier versi�n posterior. "" Este programa se distribuye con la
esperanza de que sea �til, "pero SIN NINGUNA GARANT�A, incluso sin la garant�a
impl�cita de 'o IDONEIDAD PARA UN PROP�SITO PARTICULAR. Ver la "GNU General Public
License para m�s detalles." "Usted deber�a haber recibido una copia de la GNU
General Public License" junto con este programa, si no, escriba a la Free Software
'Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE.UU..
<http://www.gnu.org/licenses/> '"Contacto: David Ireland, DI Management Services
Pty Ltd' <http://www.di-mgt.com.au> '<http://www. > di-mgt.com.au/contactmsg.php
'<http://www.cryptosys.net> Const ncSIZE As Integer = 9 Const ncINDEXLEN As Integer
= ncSIZE * ncSIZE Tipo Valor udtSQUARE As Integer '0 = no establecido, de lo
contrario valor 1 .. 9 Possibles ( ncSIZE ) As Integer '1 = 0 es posible, = no es
posible GuessLevel As Integer '0 = firme, m�s nivel de adivinar 1,2,3, ... Teniendo
en cuenta As Boolean True 'si se le da en el problema nRow As Integer 'Para la
b�squeda r�pida. Establecidos por InitPuzzle nCol As Integer '�dem NBox As Integer
'�dem End Type 'matriz Almacenar en un array lineal, una basada en lo ignore (0).
P�blicas cuadrados ( ncSIZE * ncSIZE ) Como udtSQUARE "A nivel mundial en la que
estamos adivinar (0 = empresa) privada mnGuessLevel As Integer '�ndices de
conjeturas que ya hemos tratado (esperemos que no demasiados) Const ncGUESSEDMAX As
Integer = 12 'n�mero arbitrario privado adivinado ( ncGUESSEDMAX ) As Integer
'Dificultad P�blica mnDifficulty Como la Funci�n P�blica entero DoPuzzle () Dim
BadIndex As Integer 'Crear la matriz de llamadas InitPuzzle 'Leer los datos en la
matriz BadIndex = ReadInput () Si BadIndex <> 0 Entonces MsgBox "los datos de
entrada no es v�lida. Problema con (" y GetRow ( BadIndex ) y "", y GetCol
( BadIndex ) y ")" , vbCritical End Function Si la salida de depuraci�n . Imprimir
"En el comienzo, valores perdidos =" y MissingValues ??() 'Intenta resolver sin una
conjetura llamada TrySolve Si MissingValues ??()> 0 Luego, "Ahora vamos a tener de
adivinar, posiblemente de forma recursiva llamada TryGuess End If Si
MissingValues ??() = 0 Entonces MsgBox "Hemos encontrado una soluci�n. nivel de
dificultad = problema" y FillInResults mnDifficulty m�s si vbOK = MsgBox ( "Lo
siento, no pod�a resolver. �Quieres que el valores conocidos llenado? " ,
vbOKCancel ) Luego FillInResults End If End If End Function Funci�n P�blica
TryGuess () As Boolean 'Trate de adivinar. Funci�n recursiva. Dim GuessIndex como
Dim entero i As Integer Dim nValue As Integer Dim nMaxGuesses As Integer Dim
GuessPossibles ( ncSIZE ) As Integer Dim TrialIndex As Integer TryGuess = Falso
mnDifficulty = mnDifficulty + 1 'Incrementa el nivel actual de adivinar lo que
puede dar marcha atr�s si fuese necesario mnGuessLevel = mnGuessLevel + una
depuraci�n . Imprimir "adivinar NIVEL =" y mnGuessLevel "Todo lo que hacemos a
partir de ahora ser� provisional ..." Verificaci�n del l�mite de lo que no duran
para siempre Si mnGuessLevel > ncGUESSEDMAX Entonces MsgBox "Intent� adivinar
demasiado!" , vbExclamation Final Exit Function Si 'Elija un cuadrado con las
tarifas m�s posibilidades # ??�con exclusi�n de cualquier conjeturas antes
GuessIndex = FindMinPossibles () "Recuerden por lo que no vuelva a intentarlo
adivinado ( mnGuessLevel ) = GuessIndex nMaxGuesses = CountPossibles ( GuessIndex )
'recordar los detalles de esta plaza central para i = 1 Para ncSIZE GuessPossibles
( i ) = Cuadrados ( GuessIndex ). Possibles ( i ) A continuaci�n de depuraci�n .
Imprimir "Adivinar por cuadrados (" y GetRow ( GuessIndex ) y "", y GetCol
( GuessIndex ) y ")" depuraci�n . nMaxGuesses de impresi�n y "valores posibles"
'Rellenar con la conjetura siguiente, el trabajo a trav�s de todos los posibles
para TrialIndex = 1 Para nMaxGuesses nValue = TheNthPossible ( GuessIndex ,
TrialIndex ) de depuraci�n . Imprimir "valor = Adivinar" y nValue Si nValue < = 0
Entonces MsgBox "Run de conjeturas" Final Exit Function Si la llamada escuadra
( nValue , GuessIndex ) Si TrySolve () A continuaci�n, "Hemos terminado la salida
para ventas de depuraci�n . Imprimir "Supongo que fracas�". Llame UndoGuess
( mnGuessLevel ) de depuraci�n . Imprimir "Despu�s de UndoGuess: Los valores
perdidos =" y MissingValues ??() End If Next depuraci�n . Imprimir ". END TryGuess
valores perdidos =" y MissingValues ??() 'Si no estamos all� todav�a, que pruebe
con otro (recursiva) Supongo que en el siguiente nivel si MissingValues ??()> 0
Luego de llamadas TryGuess End If End Function Funci�n P�blica UndoGuess ( ByVal
ThisLevel As Integer ) 'Deshacer todas las conjeturas en este "nivel y rehacer
todos los posibles, porque est�n equivocados Dim �ndice Como Dim entero i As
Integer Dim nOldLevel As Integer Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). GuessLevel = ThisLevel Luego cuadrados ( �ndice ). Valor = 0 End If
Para i = 1 Para ncSIZE cuadrados ( �ndice ). Possibles ( i ) = 1 Siguiente "Para
restablecer todos los posibles, el uso escuadra para restablecer las plazas
conocidas", pero supongo que cambiar temporalmente el nivel de cero, mientras lo
hacemos nOldLevel = mnGuessLevel Si Siguiente mnGuessLevel = depuraci�n
nOldLevel . Imprimir "Supongo que a nivel de deshecho" y mnGuessLevel Funci�n
P�blica fin TrySolve () As Boolean 'tratar de resolver con una respuesta
definitiva' Devuelve True si resuelve Dim iRound como Dim entero hecho As Boolean
Dim nPrevious As Integer mnDifficulty = mnDifficulty + 1 iRound = 0 nPrevious = 0
hacer = Falso Hacer hasta hace o nPrevious = MissingValues ??() "Recuerden el
conteo previo para que podamos dejar de nPrevious = MissingValues ??() 'Este va
primero puede resolver los problemas m�s simples absoluta Hacer mientras
SetKnownValues ??( ) iRound = iRound + una depuraci�n . Imprimir "Completado todo"
y iRound y ". Los valores perdidos =" y MissingValues ??() bucle si
MissingValues ??() = 0 Luego de depuraci�n . Imprimir "Resuelto en Primera Go!"
hace = salida verdadera acaban Si "Ahora esforzarse m�s mnDifficulty = mnDifficulty
+ 1 Hacer mientras TryEachBox () de depuraci�n . Imprimir "Trat� de cada caja. Los
valores perdidos =" y MissingValues ??() Hacer mientras SetKnownValues ??() iRound
= iRound + una depuraci�n . Imprimir "Completado todo" y iRound y ". Valores
perdidos =" y MissingValues ??() Loop Si MissingValues ??() = 0 Luego hacer =
salida verdadera Do End If Do Mientras TryEachRow () de depuraci�n . Imprimir
"Trat� de cada fila. Los valores perdidos =" y MissingValues ??() No Si
SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir "Completado todo" y
iRound y ". Los valores perdidos =" y MissingValues ??() Loop Si MissingValues ??()
= 0 Luego hacer = salida verdadera Do End If Do Mientras TryEachCol () Depuraci�n .
Imprimir "Trat� de cada col. Los valores perdidos =" y MissingValues ??() Hacer
mientras SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir
"Completado todo" y iRound y ". Valores perdidos =" y MissingValues ??() Loop Si
MissingValues ??( ) = 0 Luego hacer = salida verdadera Do End If bucle "Hasta hace
TrySolve = ( MissingValues ??() = 0 ) End Function Funci�n P�blica AlreadyGuessed (
ThisIndex As Integer ) As Boolean 'Devuelve True si ya hemos adivinado el valor de
este �ndice "a un nivel inferior (es decir, mnGuessLevel ya se ha incrementado) Dim
i As Integer Para i = 1 Para mnGuessLevel - 1 Si adivinado ( i ) = ThisIndex Luego
AlreadyGuessed = true Para Salir End If Next End Function Funci�n P�blica
FindMinPossibles () As Integer "m�s bajo �ndice de devoluciones a una plaza sin
resolver por el n � posibilidades" con exclusi�n de cualquier conjeturas antes en
los niveles inferiores Dim Indice As Integer Dim nMin As Integer Dim nMinIndex As
Integer nMin = ncSIZE + 1 Por �ndice = 1 Para ncINDEXLEN Si cuadrados ( �ndice ).
Valor = 0 Y CountPossibles ( �ndice ) < nMin Entonces Si no AlreadyGuessed ( �ndice
) Luego nMin = CountPossibles ( �ndice ) nMinIndex = �ndice End If End If Next
FindMinPossibles = nMinIndex End Function Funci�n P�blica TryEachBox () As Boolean
'Trate a todos los candidatos de cada caja, hasta que nos encontramos con algo
nuevo: "Si encontramos una nueva, detener, ajustar el valor y el retorno True 'Si
no hay suerte, devuelva False Dim iBox As Integer Dim iValue As Integer Dim n As
Integer Dim nFoundAt As Integer TryEachBox = False para iBox = 1 A ncSIZE Para
iValue = 1 Para ncSIZE n = PossiblesInBox ( iValue , iBox , nFoundAt ) Si n = 1 A
continuaci�n, "Marque esta no est� configurado Si cuadrados ( nFoundAt ). Valor = 0
A continuaci�n, "�Hurra! Hemos resuelto esta plaza llamada escuadra ( iValue ,
nFoundAt ) "No vayamos m�s lejos ahora TryEachBox = True End If End Exit Function
Si Siguiente End Function Public Function TryEachRow () As Boolean 'Trate a todos
los candidatos para cada fila hasta que encontremos algo nueva 'Si encontramos una
nueva, detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva
False Dim IRow As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As
Integer TryEachRow = False para IRow = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n
= PossiblesInRow ( iValue , IRow , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachRow = True End If End Exit Function Si Siguiente End Function
Public Function TryEachCol () As Boolean 'Trate a todos los candidatos
para cada columna hasta que encontremos algo nueva 'Si encontramos una nueva,
detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva False Dim
iCol As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As Integer
TryEachCol = False para iCol = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n =
PossiblesInCol ( iValue , iCol , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachCol = True End Exit Function End If Next Si Final de la Funci�n
P�blica Funci�n PossiblesInBox ( ThisValue As Integer , NBox As Integer , ByRef
FoundAt As Integer ) ' Devoluciones no de los posibles para este valor en esta
"caja y se pone FoundAt a ser el �ndice, donde la �ltima vez que encontr� una
posible este valor Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt
= �ndice End If End If Next PossiblesInBox = n End Function Funci�n P�blica
PossiblesInRow ( ThisValue As Integer , nRow As Integer , ByRef FoundAt As
Integer ) 'Devuelve no de los posibles para este valor en esta l�nea " y establece
FoundAt a ser el �ndice, donde la �ltima vez que encontr� una posible este valor
Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt = �ndice End If
End If Next PossiblesInRow = n End Function Public Function PossiblesInCol
( ThisValue As Integer , nCol As Integer , ByRef FoundAt As Integer ) 'Devuelve no
de los posibles para este valor en este col' y establece FoundAt a ser el �ndice,
donde la �ltima vez que encontr� una posible este valor Dim Indice As Integer Dim n
como > 0 entonces n = n + 1 FoundAt = �ndice End If End If Next PossiblesInCol = n
End Function Public Function MissingValues ??() As Integer no el n�mero
"Devoluciones de escuadras. Si es cero, tenemos una soluci�n completa. Dim Indice
As Integer Dim n As Integer n = 0 Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). Valor = 0 Luego, n = n + 1 End If Next MissingValues ??= n End Function
Funci�n P�blica SetKnownValues ??() As Boolean 'Comprueba si simple eliminaci�n de
los posibles nos da ninguna soluci�n' Devuelve True si se hace un cambio o falso si
no hay cambios en este paso Dim Indice As Integer Dim iValue As Integer Dim
bChanged As Boolean bChanged = False �ndice = 1 Para ncINDEXLEN Si CountPossibles (
�ndice ) = 1 Y cuadrados ( �ndice ). Valor = 0 A continuaci�n, 'encontrado otra
respuesta iValue = ThePossible ( �ndice ) de depuraci�n . Imprimir "Se ha
encontrado de valor (" y GetRow ( �ndice ) y "", y GetCol ( �ndice de ) y ") =" y
iValue 'Establecer el valor (y eliminar los posibles m�s) Llame a escuadra ( iValue
, �ndice ) bChanged = True End If Next depuraci�n . Imprimir "SetKnownValues:" y
SiInm ( bChanged , "encontrado m�s ..." , "NO HAY CAMBIOS esta ronda" )
SetKnownValues ??= bChanged End Function Public Function CountPossibles ( �ndice de
As Integer ) As Integer 'N�mero no de los valores que son posibles para esta plaza:
"Si, tenemos la" soluci�n Si es cero, tenemos un error Dim i As Integer Dim n As
Integer n = 0 para i = 1 Para ncSIZE n = n + cuadrados ( �ndice ). Possibles ( i )
Siguiente CountPossibles = n End Function Funci�n P�blica ThePossible ( �ndice de
As Integer ) As Integer 'Se supone s�lo un posible valor Dim i As Integer Para i =
1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 Entonces ThePossible = i
Exit For End If Next End Funci�n P�blica Funci�n TheNthPossible ( �ndice de As
Integer , n_th As Integer ) As Integer ' encuentra el valor n posible para esta
plaza (base 1) Dim i As Integer Dim nValue As Integer Dim n As Integer n = n_th
Para i = 1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 entonces n = n
- 1 Si n = 0 Luego nValue = i Exit For End If End If Next TheNthPossible = nValue
End Function Funci�n P�blica IsDataOK () As Integer 'Devuelve cero si los datos son
correctos, el �ndice m�s del primer error Dim Indice As Integer IsDataOK = 0 '
inocente hasta que se demuestre < = 0 Luego IsDataOK = �ndice de Exit For End If
Next End Function Public Function escuadra ( iValue As Integer , ThisIndex As
Integer ) As Boolean 'Establecer el valor plaza y eliminar todos los posibles en la
misma fila, columna y caja de Dim i As Integer cuadrados ( ThisIndex ). Valor =
iValue = 0 End If Si cuadrados ( i ). nCol = Cuadrados ( ThisIndex ). nCol Luego
cuadrados ( i ). Possibles ( iValue ) = 0 End If Si cuadrados ( i ). NBox =
Cuadrados ( ThisIndex ). NBox Luego cuadrados ( i ). Possibles ( iValue ) = 0 End
If Next 'y aseg�rese de Possibles esta plaza se han establecido correctamente para
i = 1 Para ncSIZE cuadrados ( ThisIndex ). Possibles ( i ) = 0 Siguiente cuadrados
( ThisIndex ). Possibles ( iValue ) = 1 escuadra = True End Funci�n P�blica Funci�n
SetSquareRC ( iValue As Integer , IRow As Integer , iCol As Integer , opcional
IsGiven As Boolean ) As Boolean Valor de ajuste cuadrado "dado (fila, columna).
Opcionalmente, establecer la etiqueta dada. Dim Indice As Integer �ndice = getIndex
( IRow , iCol ) Cuadrados ( �ndice ). Teniendo en cuenta = IsGiven SetSquareRC =
escuadra ( iValue , �ndice ) End Function Public Function FillInResults () Dim rng
Como Range Dim IRow As Integer , iCol As Integer Dim iValue As Integer Dim �ndice
como conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) Si cuadrados ( �ndice ).
Teniendo en cuenta entonces 'Just formato para mostrar que era un hecho generador
de n�meros aleatorios ( IRow , iCol ). Interior . ColorIndex = 6 rng ( IRow ,
iCol ). Fuente . Negrita = verdadero cuadrados ElseIf ( �ndice ). Valor > 0 Luego
encontrado una soluci�n rng ( IRow , iCol ). Valor = Cuadrados ( �ndice ). rng
Valor ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = False End If Next Next End Funci�n P�blica ClearGrid () Dim rng Como
Range Dim IRow As Integer , iCol As Integer Dim iValue como Dim entero �ndice como
conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para iCol
= 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) rng ( IRow , iCol ) . Valor = ""
rng ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = Falso Siguiente End Function Public Function ReadInput () As Integer 0
"si el �ndice m�s bien de la plaza con el problema Dim rng Como Range Dim wkb Como
libro Dim IRow As Integer , iCol As Integer Dim iValue As Integer Set wkb =
ActiveWorkbook Set rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE iValue = Val ( rng . art�culo ( IRow , iCol )) Si iValue > 0
Luego, "tienda le da un valor en la matriz Si no SetSquareRC ( iValue , IRow , iCol
, cierto ) Entonces MsgBox "entrada no v�lida en (" y IRow y "," y iCol y ") "
Final Exit Function End If Si Siguiente ReadInput = IsDataOK () End Function
Funci�n P�blica InitPuzzle () 'Inicializar las Plazas de la matriz Dim IRow As
Integer , iCol As Integer Dim �ndice Como Dim entero i As Integer 'init todos los
valores por �ndice = 1 Para ncINDEXLEN cuadrados ( �ndice ). Teniendo en cuenta =
Falso cuadrados ( �ndice ). GuessLevel = 0 Cuadrados ( �ndice ). Valor = 0
Siguiente Para i = 1 Para ncGUESSEDMAX adivinado ( i ) = 0 Siguiente 'Set todos los
posibles para un para �ndice = 1 Para ncINDEXLEN Para i = 1 Para ncSIZE cuadrados (
�ndice ). Possibles ( i ) = 1 Siguiente 'Ajuste el nivel de adivinar mundial
mnGuessLevel = 0 mnDifficulty = 0 'Inicializar el n�mero de fila, columna y la caja
"para agilizar las b�squedas" (Estos se podr�a hacer con las constantes, pero esto
es m�s f�cil) 'fila almacenados columna x, base-1 Para iCol = 1 a 9 para IRow = 1 a
9 �ndice = getIndex ( IRow , iCol ) Cuadrados ( �ndice ). nRow = IRow cuadrados
( �ndice ). nCol = iCol Siguiente 'n�meros Set caja 1 .. 9' (hay sin duda un
algoritmo sencillo, pero esta Funci�n P�blica getIndex ( IRow As Integer , iCol As
Integer ) As Integer dado "valor de retorno (IRow, iCol) del �ndice (1 .. 81)
getIndex = ( IRow - 1 ) * ncSIZE + iCol End Function Public Function GetRow
( iIndex As Integer ) As Integer GetRow = (( iIndex - 1 ) \ ncSIZE ) + 1 End
Function Public Function GetCol ( iIndex As Integer ) As Integer GetCol = (( iIndex
- 1 ) Mod ncSIZE ) + 1 End Function Public Function GetBox ( iIndex As Integer ) As
Integer Dim nRow As Integer , nCol como Dim entero nBand como Dim entero nStack As
Integer nRow = GetRow ( iIndex ) nCol = GetCol ( iIndex ) nBand = ( nRow - 1 ) \ 3
+ 1 nStack = ( nCol - 1 ) \ 3 + 1 GetBox = ( nBand - 1 ) * 3 + nStack End Function
Funci�n P�blica InThisRow ( TheValue As Integer , TheIndex As Integer ) As Boolean
Dim �ndice Como Dim entero nRow como Por End If End If Next End Function Public
Function InThisCol ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero nCol como Por End If End If Next End Function Public
Function InThisBox ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero NBox como Por End If End If Next End Function Sub
Button1_Click () DoPuzzle End Sub Sub Button3_Click () ClearGrid End Sub

Option Explicit 'Este c�digo intenta solucionar los problemas de 9x9 Su Doku.'
'Copyright (C) 2004 David Ireland', 'Este programa es software libre, puede
redistribuirlo y / o "modificado bajo los t�rminos de la Licencia P�blica General
de GNU" publicada por la Free Software Foundation, versi�n 2 'de la Licencia, o (a
su elecci�n) cualquier versi�n posterior. "" Este programa se distribuye con la
esperanza de que sea �til, "pero SIN NINGUNA GARANT�A, incluso sin la garant�a
impl�cita de 'o IDONEIDAD PARA UN PROP�SITO PARTICULAR. Ver la "GNU General Public
License para m�s detalles." "Usted deber�a haber recibido una copia de la GNU
General Public License" junto con este programa, si no, escriba a la Free Software
'Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE.UU..
<http://www.gnu.org/licenses/> '"Contacto: David Ireland, DI Management Services
Pty Ltd' <http://www.di-mgt.com.au> '<http://www. > di-mgt.com.au/contactmsg.php
'<http://www.cryptosys.net> Const ncSIZE As Integer = 9 Const ncINDEXLEN As Integer
= ncSIZE * ncSIZE Tipo Valor udtSQUARE As Integer '0 = no establecido, de lo
contrario valor 1 .. 9 Possibles ( ncSIZE ) As Integer '1 = 0 es posible, = no es
posible GuessLevel As Integer '0 = firme, m�s nivel de adivinar 1,2,3, ... Teniendo
en cuenta As Boolean True 'si se le da en el problema nRow As Integer 'Para la
b�squeda r�pida. Establecidos por InitPuzzle nCol As Integer '�dem NBox As Integer
'�dem End Type 'matriz Almacenar en un array lineal, una basada en lo ignore (0).
P�blicas cuadrados ( ncSIZE * ncSIZE ) Como udtSQUARE "A nivel mundial en la que
estamos adivinar (0 = empresa) privada mnGuessLevel As Integer '�ndices de
conjeturas que ya hemos tratado (esperemos que no demasiados) Const ncGUESSEDMAX As
Integer = 12 'n�mero arbitrario privado adivinado ( ncGUESSEDMAX ) As Integer
'Dificultad P�blica mnDifficulty Como la Funci�n P�blica entero DoPuzzle () Dim
BadIndex As Integer 'Crear la matriz de llamadas InitPuzzle 'Leer los datos en la
matriz BadIndex = ReadInput () Si BadIndex <> 0 Entonces MsgBox "los datos de
entrada no es v�lida. Problema con (" y GetRow ( BadIndex ) y "", y GetCol
( BadIndex ) y ")" , vbCritical End Function Si la salida de depuraci�n . Imprimir
"En el comienzo, valores perdidos =" y MissingValues ??() 'Intenta resolver sin una
conjetura llamada TrySolve Si MissingValues ??()> 0 Luego, "Ahora vamos a tener de
adivinar, posiblemente de forma recursiva llamada TryGuess End If Si
MissingValues ??() = 0 Entonces MsgBox "Hemos encontrado una soluci�n. nivel de
dificultad = problema" y FillInResults mnDifficulty m�s si vbOK = MsgBox ( "Lo
siento, no pod�a resolver. �Quieres que el valores conocidos llenado? " ,
vbOKCancel ) Luego FillInResults End If End If End Function Funci�n P�blica
TryGuess () As Boolean 'Trate de adivinar. Funci�n recursiva. Dim GuessIndex como
Dim entero i As Integer Dim nValue As Integer Dim nMaxGuesses As Integer Dim
GuessPossibles ( ncSIZE ) As Integer Dim TrialIndex As Integer TryGuess = Falso
mnDifficulty = mnDifficulty + 1 'Incrementa el nivel actual de adivinar lo que
puede dar marcha atr�s si fuese necesario mnGuessLevel = mnGuessLevel + una
depuraci�n . Imprimir "adivinar NIVEL =" y mnGuessLevel "Todo lo que hacemos a
partir de ahora ser� provisional ..." Verificaci�n del l�mite de lo que no duran
para siempre Si mnGuessLevel > ncGUESSEDMAX Entonces MsgBox "Intent� adivinar
demasiado!" , vbExclamation Final Exit Function Si 'Elija un cuadrado con las
tarifas m�s posibilidades # ??�con exclusi�n de cualquier conjeturas antes
GuessIndex = FindMinPossibles () "Recuerden por lo que no vuelva a intentarlo
adivinado ( mnGuessLevel ) = GuessIndex nMaxGuesses = CountPossibles ( GuessIndex )
'recordar los detalles de esta plaza central para i = 1 Para ncSIZE GuessPossibles
( i ) = Cuadrados ( GuessIndex ). Possibles ( i ) A continuaci�n de depuraci�n .
Imprimir "Adivinar por cuadrados (" y GetRow ( GuessIndex ) y "", y GetCol
( GuessIndex ) y ")" depuraci�n . nMaxGuesses de impresi�n y "valores posibles"
'Rellenar con la conjetura siguiente, el trabajo a trav�s de todos los posibles
para TrialIndex = 1 Para nMaxGuesses nValue = TheNthPossible ( GuessIndex ,
TrialIndex ) de depuraci�n . Imprimir "valor = Adivinar" y nValue Si nValue < = 0
Entonces MsgBox "Run de conjeturas" Final Exit Function Si la llamada escuadra
( nValue , GuessIndex ) Si TrySolve () A continuaci�n, "Hemos terminado la salida
para ventas de depuraci�n . Imprimir "Supongo que fracas�". Llame UndoGuess
( mnGuessLevel ) de depuraci�n . Imprimir "Despu�s de UndoGuess: Los valores
perdidos =" y MissingValues ??() End If Next depuraci�n . Imprimir ". END TryGuess
valores perdidos =" y MissingValues ??() 'Si no estamos all� todav�a, que pruebe
con otro (recursiva) Supongo que en el siguiente nivel si MissingValues ??()> 0
Luego de llamadas TryGuess End If End Function Funci�n P�blica UndoGuess ( ByVal
ThisLevel As Integer ) 'Deshacer todas las conjeturas en este "nivel y rehacer
todos los posibles, porque est�n equivocados Dim �ndice Como Dim entero i As
Integer Dim nOldLevel As Integer Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). GuessLevel = ThisLevel Luego cuadrados ( �ndice ). Valor = 0 End If
Para i = 1 Para ncSIZE cuadrados ( �ndice ). Possibles ( i ) = 1 Siguiente "Para
restablecer todos los posibles, el uso escuadra para restablecer las plazas
conocidas", pero supongo que cambiar temporalmente el nivel de cero, mientras lo
hacemos nOldLevel = mnGuessLevel Si Siguiente mnGuessLevel = depuraci�n
nOldLevel . Imprimir "Supongo que a nivel de deshecho" y mnGuessLevel Funci�n
P�blica fin TrySolve () As Boolean 'tratar de resolver con una respuesta
definitiva' Devuelve True si resuelve Dim iRound como Dim entero hecho As Boolean
Dim nPrevious As Integer mnDifficulty = mnDifficulty + 1 iRound = 0 nPrevious = 0
hacer = Falso Hacer hasta hace o nPrevious = MissingValues ??() "Recuerden el
conteo previo para que podamos dejar de nPrevious = MissingValues ??() 'Este va
primero puede resolver los problemas m�s simples absoluta Hacer mientras
SetKnownValues ??( ) iRound = iRound + una depuraci�n . Imprimir "Completado todo"
y iRound y ". Los valores perdidos =" y MissingValues ??() bucle si
MissingValues ??() = 0 Luego de depuraci�n . Imprimir "Resuelto en Primera Go!"
hace = salida verdadera acaban Si "Ahora esforzarse m�s mnDifficulty = mnDifficulty
+ 1 Hacer mientras TryEachBox () de depuraci�n . Imprimir "Trat� de cada caja. Los
valores perdidos =" y MissingValues ??() Hacer mientras SetKnownValues ??() iRound
= iRound + una depuraci�n . Imprimir "Completado todo" y iRound y ". Valores
perdidos =" y MissingValues ??() Loop Si MissingValues ??() = 0 Luego hacer =
salida verdadera Do End If Do Mientras TryEachRow () de depuraci�n . Imprimir
"Trat� de cada fila. Los valores perdidos =" y MissingValues ??() No Si
SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir "Completado todo" y
iRound y ". Los valores perdidos =" y MissingValues ??() Loop Si MissingValues ??()
= 0 Luego hacer = salida verdadera Do End If Do Mientras TryEachCol () Depuraci�n .
Imprimir "Trat� de cada col. Los valores perdidos =" y MissingValues ??() Hacer
mientras SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir
"Completado todo" y iRound y ". Valores perdidos =" y MissingValues ??() Loop Si
MissingValues ??( ) = 0 Luego hacer = salida verdadera Do End If bucle "Hasta hace
TrySolve = ( MissingValues ??() = 0 ) End Function Funci�n P�blica AlreadyGuessed (
ThisIndex As Integer ) As Boolean 'Devuelve True si ya hemos adivinado el valor de
este �ndice "a un nivel inferior (es decir, mnGuessLevel ya se ha incrementado) Dim
i As Integer Para i = 1 Para mnGuessLevel - 1 Si adivinado ( i ) = ThisIndex Luego
AlreadyGuessed = true Para Salir End If Next End Function Funci�n P�blica
FindMinPossibles () As Integer "m�s bajo �ndice de devoluciones a una plaza sin
resolver por el n � posibilidades" con exclusi�n de cualquier conjeturas antes en
los niveles inferiores Dim Indice As Integer Dim nMin As Integer Dim nMinIndex As
Integer nMin = ncSIZE + 1 Por �ndice = 1 Para ncINDEXLEN Si cuadrados ( �ndice ).
Valor = 0 Y CountPossibles ( �ndice ) < nMin Entonces Si no AlreadyGuessed ( �ndice
) Luego nMin = CountPossibles ( �ndice ) nMinIndex = �ndice End If End If Next
FindMinPossibles = nMinIndex End Function Funci�n P�blica TryEachBox () As Boolean
'Trate a todos los candidatos de cada caja, hasta que nos encontramos con algo
nuevo: "Si encontramos una nueva, detener, ajustar el valor y el retorno True 'Si
no hay suerte, devuelva False Dim iBox As Integer Dim iValue As Integer Dim n As
Integer Dim nFoundAt As Integer TryEachBox = False para iBox = 1 A ncSIZE Para
iValue = 1 Para ncSIZE n = PossiblesInBox ( iValue , iBox , nFoundAt ) Si n = 1 A
continuaci�n, "Marque esta no est� configurado Si cuadrados ( nFoundAt ). Valor = 0
A continuaci�n, "�Hurra! Hemos resuelto esta plaza llamada escuadra ( iValue ,
nFoundAt ) "No vayamos m�s lejos ahora TryEachBox = True End If End Exit Function
Si Siguiente End Function Public Function TryEachRow () As Boolean 'Trate a todos
los candidatos para cada fila hasta que encontremos algo nueva 'Si encontramos una
nueva, detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva
False Dim IRow As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As
Integer TryEachRow = False para IRow = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n
= PossiblesInRow ( iValue , IRow , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachRow = True End If End Exit Function Si Siguiente End Function
Public Function TryEachCol () As Boolean 'Trate a todos los candidatos
para cada columna hasta que encontremos algo nueva 'Si encontramos una nueva,
detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva False Dim
iCol As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As Integer
TryEachCol = False para iCol = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n =
PossiblesInCol ( iValue , iCol , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachCol = True End Exit Function End If Next Si Final de la Funci�n
P�blica Funci�n PossiblesInBox ( ThisValue As Integer , NBox As Integer , ByRef
FoundAt As Integer ) ' Devoluciones no de los posibles para este valor en esta
"caja y se pone FoundAt a ser el �ndice, donde la �ltima vez que encontr� una
posible este valor Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt
= �ndice End If End If Next PossiblesInBox = n End Function Funci�n P�blica
PossiblesInRow ( ThisValue As Integer , nRow As Integer , ByRef FoundAt As
Integer ) 'Devuelve no de los posibles para este valor en esta l�nea " y establece
FoundAt a ser el �ndice, donde la �ltima vez que encontr� una posible este valor
Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt = �ndice End If
End If Next PossiblesInRow = n End Function Public Function PossiblesInCol
( ThisValue As Integer , nCol As Integer , ByRef FoundAt As Integer ) 'Devuelve no
de los posibles para este valor en este col' y establece FoundAt a ser el �ndice,
donde la �ltima vez que encontr� una posible este valor Dim Indice As Integer Dim n
como > 0 entonces n = n + 1 FoundAt = �ndice End If End If Next PossiblesInCol = n
End Function Public Function MissingValues ??() As Integer no el n�mero
"Devoluciones de escuadras. Si es cero, tenemos una soluci�n completa. Dim Indice
As Integer Dim n As Integer n = 0 Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). Valor = 0 Luego, n = n + 1 End If Next MissingValues ??= n End Function
Funci�n P�blica SetKnownValues ??() As Boolean 'Comprueba si simple eliminaci�n de
los posibles nos da ninguna soluci�n' Devuelve True si se hace un cambio o falso si
no hay cambios en este paso Dim Indice As Integer Dim iValue As Integer Dim
bChanged As Boolean bChanged = False �ndice = 1 Para ncINDEXLEN Si CountPossibles (
�ndice ) = 1 Y cuadrados ( �ndice ). Valor = 0 A continuaci�n, 'encontrado otra
respuesta iValue = ThePossible ( �ndice ) de depuraci�n . Imprimir "Se ha
encontrado de valor (" y GetRow ( �ndice ) y "", y GetCol ( �ndice de ) y ") =" y
iValue 'Establecer el valor (y eliminar los posibles m�s) Llame a escuadra ( iValue
, �ndice ) bChanged = True End If Next depuraci�n . Imprimir "SetKnownValues:" y
SiInm ( bChanged , "encontrado m�s ..." , "NO HAY CAMBIOS esta ronda" )
SetKnownValues ??= bChanged End Function Public Function CountPossibles ( �ndice de
As Integer ) As Integer 'N�mero no de los valores que son posibles para esta plaza:
"Si, tenemos la" soluci�n Si es cero, tenemos un error Dim i As Integer Dim n As
Integer n = 0 para i = 1 Para ncSIZE n = n + cuadrados ( �ndice ). Possibles ( i )
Siguiente CountPossibles = n End Function Funci�n P�blica ThePossible ( �ndice de
As Integer ) As Integer 'Se supone s�lo un posible valor Dim i As Integer Para i =
1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 Entonces ThePossible = i
Exit For End If Next End Funci�n P�blica Funci�n TheNthPossible ( �ndice de As
Integer , n_th As Integer ) As Integer ' encuentra el valor n posible para esta
plaza (base 1) Dim i As Integer Dim nValue As Integer Dim n As Integer n = n_th
Para i = 1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 entonces n = n
- 1 Si n = 0 Luego nValue = i Exit For End If End If Next TheNthPossible = nValue
End Function Funci�n P�blica IsDataOK () As Integer 'Devuelve cero si los datos son
correctos, el �ndice m�s del primer error Dim Indice As Integer IsDataOK = 0 '
inocente hasta que se demuestre < = 0 Luego IsDataOK = �ndice de Exit For End If
Next End Function Public Function escuadra ( iValue As Integer , ThisIndex As
Integer ) As Boolean 'Establecer el valor plaza y eliminar todos los posibles en la
misma fila, columna y caja de Dim i As Integer cuadrados ( ThisIndex ). Valor =
iValue = 0 End If Si cuadrados ( i ). nCol = Cuadrados ( ThisIndex ). nCol Luego
cuadrados ( i ). Possibles ( iValue ) = 0 End If Si cuadrados ( i ). NBox =
Cuadrados ( ThisIndex ). NBox Luego cuadrados ( i ). Possibles ( iValue ) = 0 End
If Next 'y aseg�rese de Possibles esta plaza se han establecido correctamente para
i = 1 Para ncSIZE cuadrados ( ThisIndex ). Possibles ( i ) = 0 Siguiente cuadrados
( ThisIndex ). Possibles ( iValue ) = 1 escuadra = True End Funci�n P�blica Funci�n
SetSquareRC ( iValue As Integer , IRow As Integer , iCol As Integer , opcional
IsGiven As Boolean ) As Boolean Valor de ajuste cuadrado "dado (fila, columna).
Opcionalmente, establecer la etiqueta dada. Dim Indice As Integer �ndice = getIndex
( IRow , iCol ) Cuadrados ( �ndice ). Teniendo en cuenta = IsGiven SetSquareRC =
escuadra ( iValue , �ndice ) End Function Public Function FillInResults () Dim rng
Como Range Dim IRow As Integer , iCol As Integer Dim iValue As Integer Dim �ndice
como conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) Si cuadrados ( �ndice ).
Teniendo en cuenta entonces 'Just formato para mostrar que era un hecho generador
de n�meros aleatorios ( IRow , iCol ). Interior . ColorIndex = 6 rng ( IRow ,
iCol ). Fuente . Negrita = verdadero cuadrados ElseIf ( �ndice ). Valor > 0 Luego
encontrado una soluci�n rng ( IRow , iCol ). Valor = Cuadrados ( �ndice ). rng
Valor ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = False End If Next Next End Funci�n P�blica ClearGrid () Dim rng Como
Range Dim IRow As Integer , iCol As Integer Dim iValue como Dim entero �ndice como
conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para iCol
= 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) rng ( IRow , iCol ) . Valor = ""
rng ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = Falso Siguiente End Function Public Function ReadInput () As Integer 0
"si el �ndice m�s bien de la plaza con el problema Dim rng Como Range Dim wkb Como
libro Dim IRow As Integer , iCol As Integer Dim iValue As Integer Set wkb =
ActiveWorkbook Set rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE iValue = Val ( rng . art�culo ( IRow , iCol )) Si iValue > 0
Luego, "tienda le da un valor en la matriz Si no SetSquareRC ( iValue , IRow , iCol
, cierto ) Entonces MsgBox "entrada no v�lida en (" y IRow y "," y iCol y ") "
Final Exit Function End If Si Siguiente ReadInput = IsDataOK () End Function
Funci�n P�blica InitPuzzle () 'Inicializar las Plazas de la matriz Dim IRow As
Integer , iCol As Integer Dim �ndice Como Dim entero i As Integer 'init todos los
valores por �ndice = 1 Para ncINDEXLEN cuadrados ( �ndice ). Teniendo en cuenta =
Falso cuadrados ( �ndice ). GuessLevel = 0 Cuadrados ( �ndice ). Valor = 0
Siguiente Para i = 1 Para ncGUESSEDMAX adivinado ( i ) = 0 Siguiente 'Set todos los
posibles para un para �ndice = 1 Para ncINDEXLEN Para i = 1 Para ncSIZE cuadrados (
�ndice ). Possibles ( i ) = 1 Siguiente 'Ajuste el nivel de adivinar mundial
mnGuessLevel = 0 mnDifficulty = 0 'Inicializar el n�mero de fila, columna y la caja
"para agilizar las b�squedas" (Estos se podr�a hacer con las constantes, pero esto
es m�s f�cil) 'fila almacenados columna x, base-1 Para iCol = 1 a 9 para IRow = 1 a
9 �ndice = getIndex ( IRow , iCol ) Cuadrados ( �ndice ). nRow = IRow cuadrados
( �ndice ). nCol = iCol Siguiente 'n�meros Set caja 1 .. 9' (hay sin duda un
algoritmo sencillo, pero esta Funci�n P�blica getIndex ( IRow As Integer , iCol As
Integer ) As Integer dado "valor de retorno (IRow, iCol) del �ndice (1 .. 81)
getIndex = ( IRow - 1 ) * ncSIZE + iCol End Function Public Function GetRow
( iIndex As Integer ) As Integer GetRow = (( iIndex - 1 ) \ ncSIZE ) + 1 End
Function Public Function GetCol ( iIndex As Integer ) As Integer GetCol = (( iIndex
- 1 ) Mod ncSIZE ) + 1 End Function Public Function GetBox ( iIndex As Integer ) As
Integer Dim nRow As Integer , nCol como Dim entero nBand como Dim entero nStack As
Integer nRow = GetRow ( iIndex ) nCol = GetCol ( iIndex ) nBand = ( nRow - 1 ) \ 3
+ 1 nStack = ( nCol - 1 ) \ 3 + 1 GetBox = ( nBand - 1 ) * 3 + nStack End Function
Funci�n P�blica InThisRow ( TheValue As Integer , TheIndex As Integer ) As Boolean
Dim �ndice Como Dim entero nRow como Por End If End If Next End Function Public
Function InThisCol ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero nCol como Por End If End If Next End Function Public
Function InThisBox ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero NBox como Por End If End If Next End Function Sub
Button1_Click () DoPuzzle End Sub Sub Button3_Click () ClearGrid End Sub

Option Explicit 'Este c�digo intenta solucionar los problemas de 9x9 Su Doku.'
'Copyright (C) 2004 David Ireland', 'Este programa es software libre, puede
redistribuirlo y / o "modificado bajo los t�rminos de la Licencia P�blica General
de GNU" publicada por la Free Software Foundation, versi�n 2 'de la Licencia, o (a
su elecci�n) cualquier versi�n posterior. "" Este programa se distribuye con la
esperanza de que sea �til, "pero SIN NINGUNA GARANT�A, incluso sin la garant�a
impl�cita de 'o IDONEIDAD PARA UN PROP�SITO PARTICULAR. Ver la "GNU General Public
License para m�s detalles." "Usted deber�a haber recibido una copia de la GNU
General Public License" junto con este programa, si no, escriba a la Free Software
'Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE.UU..
<http://www.gnu.org/licenses/> '"Contacto: David Ireland, DI Management Services
Pty Ltd' <http://www.di-mgt.com.au> '<http://www. > di-mgt.com.au/contactmsg.php
'<http://www.cryptosys.net> Const ncSIZE As Integer = 9 Const ncINDEXLEN As Integer
= ncSIZE * ncSIZE Tipo Valor udtSQUARE As Integer '0 = no establecido, de lo
contrario valor 1 .. 9 Possibles ( ncSIZE ) As Integer '1 = 0 es posible, = no es
posible GuessLevel As Integer '0 = firme, m�s nivel de adivinar 1,2,3, ... Teniendo
en cuenta As Boolean True 'si se le da en el problema nRow As Integer 'Para la
b�squeda r�pida. Establecidos por InitPuzzle nCol As Integer '�dem NBox As Integer
'�dem End Type 'matriz Almacenar en un array lineal, una basada en lo ignore (0).
P�blicas cuadrados ( ncSIZE * ncSIZE ) Como udtSQUARE "A nivel mundial en la que
estamos adivinar (0 = empresa) privada mnGuessLevel As Integer '�ndices de
conjeturas que ya hemos tratado (esperemos que no demasiados) Const ncGUESSEDMAX As
Integer = 12 'n�mero arbitrario privado adivinado ( ncGUESSEDMAX ) As Integer
'Dificultad P�blica mnDifficulty Como la Funci�n P�blica entero DoPuzzle () Dim
BadIndex As Integer 'Crear la matriz de llamadas InitPuzzle 'Leer los datos en la
matriz BadIndex = ReadInput () Si BadIndex <> 0 Entonces MsgBox "los datos de
entrada no es v�lida. Problema con (" y GetRow ( BadIndex ) y "", y GetCol
( BadIndex ) y ")" , vbCritical End Function Si la salida de depuraci�n . Imprimir
"En el comienzo, valores perdidos =" y MissingValues ??() 'Intenta resolver sin una
conjetura llamada TrySolve Si MissingValues ??()> 0 Luego, "Ahora vamos a tener de
adivinar, posiblemente de forma recursiva llamada TryGuess End If Si
MissingValues ??() = 0 Entonces MsgBox "Hemos encontrado una soluci�n. nivel de
dificultad = problema" y FillInResults mnDifficulty m�s si vbOK = MsgBox ( "Lo
siento, no pod�a resolver. �Quieres que el valores conocidos llenado? " ,
vbOKCancel ) Luego FillInResults End If End If End Function Funci�n P�blica
TryGuess () As Boolean 'Trate de adivinar. Funci�n recursiva. Dim GuessIndex como
Dim entero i As Integer Dim nValue As Integer Dim nMaxGuesses As Integer Dim
GuessPossibles ( ncSIZE ) As Integer Dim TrialIndex As Integer TryGuess = Falso
mnDifficulty = mnDifficulty + 1 'Incrementa el nivel actual de adivinar lo que
puede dar marcha atr�s si fuese necesario mnGuessLevel = mnGuessLevel + una
depuraci�n . Imprimir "adivinar NIVEL =" y mnGuessLevel "Todo lo que hacemos a
partir de ahora ser� provisional ..." Verificaci�n del l�mite de lo que no duran
para siempre Si mnGuessLevel > ncGUESSEDMAX Entonces MsgBox "Intent� adivinar
demasiado!" , vbExclamation Final Exit Function Si 'Elija un cuadrado con las
tarifas m�s posibilidades # ??�con exclusi�n de cualquier conjeturas antes
GuessIndex = FindMinPossibles () "Recuerden por lo que no vuelva a intentarlo
adivinado ( mnGuessLevel ) = GuessIndex nMaxGuesses = CountPossibles ( GuessIndex )
'recordar los detalles de esta plaza central para i = 1 Para ncSIZE GuessPossibles
( i ) = Cuadrados ( GuessIndex ). Possibles ( i ) A continuaci�n de depuraci�n .
Imprimir "Adivinar por cuadrados (" y GetRow ( GuessIndex ) y "", y GetCol
( GuessIndex ) y ")" depuraci�n . nMaxGuesses de impresi�n y "valores posibles"
'Rellenar con la conjetura siguiente, el trabajo a trav�s de todos los posibles
para TrialIndex = 1 Para nMaxGuesses nValue = TheNthPossible ( GuessIndex ,
TrialIndex ) de depuraci�n . Imprimir "valor = Adivinar" y nValue Si nValue < = 0
Entonces MsgBox "Run de conjeturas" Final Exit Function Si la llamada escuadra
( nValue , GuessIndex ) Si TrySolve () A continuaci�n, "Hemos terminado la salida
para ventas de depuraci�n . Imprimir "Supongo que fracas�". Llame UndoGuess
( mnGuessLevel ) de depuraci�n . Imprimir "Despu�s de UndoGuess: Los valores
perdidos =" y MissingValues ??() End If Next depuraci�n . Imprimir ". END TryGuess
valores perdidos =" y MissingValues ??() 'Si no estamos all� todav�a, que pruebe
con otro (recursiva) Supongo que en el siguiente nivel si MissingValues ??()> 0
Luego de llamadas TryGuess End If End Function Funci�n P�blica UndoGuess ( ByVal
ThisLevel As Integer ) 'Deshacer todas las conjeturas en este "nivel y rehacer
todos los posibles, porque est�n equivocados Dim �ndice Como Dim entero i As
Integer Dim nOldLevel As Integer Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). GuessLevel = ThisLevel Luego cuadrados ( �ndice ). Valor = 0 End If
Para i = 1 Para ncSIZE cuadrados ( �ndice ). Possibles ( i ) = 1 Siguiente "Para
restablecer todos los posibles, el uso escuadra para restablecer las plazas
conocidas", pero supongo que cambiar temporalmente el nivel de cero, mientras lo
hacemos nOldLevel = mnGuessLevel Si Siguiente mnGuessLevel = depuraci�n
nOldLevel . Imprimir "Supongo que a nivel de deshecho" y mnGuessLevel Funci�n
P�blica fin TrySolve () As Boolean 'tratar de resolver con una respuesta
definitiva' Devuelve True si resuelve Dim iRound como Dim entero hecho As Boolean
Dim nPrevious As Integer mnDifficulty = mnDifficulty + 1 iRound = 0 nPrevious = 0
hacer = Falso Hacer hasta hace o nPrevious = MissingValues ??() "Recuerden el
conteo previo para que podamos dejar de nPrevious = MissingValues ??() 'Este va
primero puede resolver los problemas m�s simples absoluta Hacer mientras
SetKnownValues ??( ) iRound = iRound + una depuraci�n . Imprimir "Completado todo"
y iRound y ". Los valores perdidos =" y MissingValues ??() bucle si
MissingValues ??() = 0 Luego de depuraci�n . Imprimir "Resuelto en Primera Go!"
hace = salida verdadera acaban Si "Ahora esforzarse m�s mnDifficulty = mnDifficulty
+ 1 Hacer mientras TryEachBox () de depuraci�n . Imprimir "Trat� de cada caja. Los
valores perdidos =" y MissingValues ??() Hacer mientras SetKnownValues ??() iRound
= iRound + una depuraci�n . Imprimir "Completado todo" y iRound y ". Valores
perdidos =" y MissingValues ??() Loop Si MissingValues ??() = 0 Luego hacer =
salida verdadera Do End If Do Mientras TryEachRow () de depuraci�n . Imprimir
"Trat� de cada fila. Los valores perdidos =" y MissingValues ??() No Si
SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir "Completado todo" y
iRound y ". Los valores perdidos =" y MissingValues ??() Loop Si MissingValues ??()
= 0 Luego hacer = salida verdadera Do End If Do Mientras TryEachCol () Depuraci�n .
Imprimir "Trat� de cada col. Los valores perdidos =" y MissingValues ??() Hacer
mientras SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir
"Completado todo" y iRound y ". Valores perdidos =" y MissingValues ??() Loop Si
MissingValues ??( ) = 0 Luego hacer = salida verdadera Do End If bucle "Hasta hace
TrySolve = ( MissingValues ??() = 0 ) End Function Funci�n P�blica AlreadyGuessed (
ThisIndex As Integer ) As Boolean 'Devuelve True si ya hemos adivinado el valor de
este �ndice "a un nivel inferior (es decir, mnGuessLevel ya se ha incrementado) Dim
i As Integer Para i = 1 Para mnGuessLevel - 1 Si adivinado ( i ) = ThisIndex Luego
AlreadyGuessed = true Para Salir End If Next End Function Funci�n P�blica
FindMinPossibles () As Integer "m�s bajo �ndice de devoluciones a una plaza sin
resolver por el n � posibilidades" con exclusi�n de cualquier conjeturas antes en
los niveles inferiores Dim Indice As Integer Dim nMin As Integer Dim nMinIndex As
Integer nMin = ncSIZE + 1 Por �ndice = 1 Para ncINDEXLEN Si cuadrados ( �ndice ).
Valor = 0 Y CountPossibles ( �ndice ) < nMin Entonces Si no AlreadyGuessed ( �ndice
) Luego nMin = CountPossibles ( �ndice ) nMinIndex = �ndice End If End If Next
FindMinPossibles = nMinIndex End Function Funci�n P�blica TryEachBox () As Boolean
'Trate a todos los candidatos de cada caja, hasta que nos encontramos con algo
nuevo: "Si encontramos una nueva, detener, ajustar el valor y el retorno True 'Si
no hay suerte, devuelva False Dim iBox As Integer Dim iValue As Integer Dim n As
Integer Dim nFoundAt As Integer TryEachBox = False para iBox = 1 A ncSIZE Para
iValue = 1 Para ncSIZE n = PossiblesInBox ( iValue , iBox , nFoundAt ) Si n = 1 A
continuaci�n, "Marque esta no est� configurado Si cuadrados ( nFoundAt ). Valor = 0
A continuaci�n, "�Hurra! Hemos resuelto esta plaza llamada escuadra ( iValue ,
nFoundAt ) "No vayamos m�s lejos ahora TryEachBox = True End If End Exit Function
Si Siguiente End Function Public Function TryEachRow () As Boolean 'Trate a todos
los candidatos para cada fila hasta que encontremos algo nueva 'Si encontramos una
nueva, detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva
False Dim IRow As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As
Integer TryEachRow = False para IRow = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n
= PossiblesInRow ( iValue , IRow , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachRow = True End If End Exit Function Si Siguiente End Function
Public Function TryEachCol () As Boolean 'Trate a todos los candidatos
para cada columna hasta que encontremos algo nueva 'Si encontramos una nueva,
detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva False Dim
iCol As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As Integer
TryEachCol = False para iCol = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n =
PossiblesInCol ( iValue , iCol , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachCol = True End Exit Function End If Next Si Final de la Funci�n
P�blica Funci�n PossiblesInBox ( ThisValue As Integer , NBox As Integer , ByRef
FoundAt As Integer ) ' Devoluciones no de los posibles para este valor en esta
"caja y se pone FoundAt a ser el �ndice, donde la �ltima vez que encontr� una
posible este valor Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt
= �ndice End If End If Next PossiblesInBox = n End Function Funci�n P�blica
PossiblesInRow ( ThisValue As Integer , nRow As Integer , ByRef FoundAt As
Integer ) 'Devuelve no de los posibles para este valor en esta l�nea " y establece
FoundAt a ser el �ndice, donde la �ltima vez que encontr� una posible este valor
Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt = �ndice End If
End If Next PossiblesInRow = n End Function Public Function PossiblesInCol
( ThisValue As Integer , nCol As Integer , ByRef FoundAt As Integer ) 'Devuelve no
de los posibles para este valor en este col' y establece FoundAt a ser el �ndice,
donde la �ltima vez que encontr� una posible este valor Dim Indice As Integer Dim n
como > 0 entonces n = n + 1 FoundAt = �ndice End If End If Next PossiblesInCol = n
End Function Public Function MissingValues ??() As Integer no el n�mero
"Devoluciones de escuadras. Si es cero, tenemos una soluci�n completa. Dim Indice
As Integer Dim n As Integer n = 0 Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). Valor = 0 Luego, n = n + 1 End If Next MissingValues ??= n End Function
Funci�n P�blica SetKnownValues ??() As Boolean 'Comprueba si simple eliminaci�n de
los posibles nos da ninguna soluci�n' Devuelve True si se hace un cambio o falso si
no hay cambios en este paso Dim Indice As Integer Dim iValue As Integer Dim
bChanged As Boolean bChanged = False �ndice = 1 Para ncINDEXLEN Si CountPossibles (
�ndice ) = 1 Y cuadrados ( �ndice ). Valor = 0 A continuaci�n, 'encontrado otra
respuesta iValue = ThePossible ( �ndice ) de depuraci�n . Imprimir "Se ha
encontrado de valor (" y GetRow ( �ndice ) y "", y GetCol ( �ndice de ) y ") =" y
iValue 'Establecer el valor (y eliminar los posibles m�s) Llame a escuadra ( iValue
, �ndice ) bChanged = True End If Next depuraci�n . Imprimir "SetKnownValues:" y
SiInm ( bChanged , "encontrado m�s ..." , "NO HAY CAMBIOS esta ronda" )
SetKnownValues ??= bChanged End Function Public Function CountPossibles ( �ndice de
As Integer ) As Integer 'N�mero no de los valores que son posibles para esta plaza:
"Si, tenemos la" soluci�n Si es cero, tenemos un error Dim i As Integer Dim n As
Integer n = 0 para i = 1 Para ncSIZE n = n + cuadrados ( �ndice ). Possibles ( i )
Siguiente CountPossibles = n End Function Funci�n P�blica ThePossible ( �ndice de
As Integer ) As Integer 'Se supone s�lo un posible valor Dim i As Integer Para i =
1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 Entonces ThePossible = i
Exit For End If Next End Funci�n P�blica Funci�n TheNthPossible ( �ndice de As
Integer , n_th As Integer ) As Integer ' encuentra el valor n posible para esta
plaza (base 1) Dim i As Integer Dim nValue As Integer Dim n As Integer n = n_th
Para i = 1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 entonces n = n
- 1 Si n = 0 Luego nValue = i Exit For End If End If Next TheNthPossible = nValue
End Function Funci�n P�blica IsDataOK () As Integer 'Devuelve cero si los datos son
correctos, el �ndice m�s del primer error Dim Indice As Integer IsDataOK = 0 '
inocente hasta que se demuestre < = 0 Luego IsDataOK = �ndice de Exit For End If
Next End Function Public Function escuadra ( iValue As Integer , ThisIndex As
Integer ) As Boolean 'Establecer el valor plaza y eliminar todos los posibles en la
misma fila, columna y caja de Dim i As Integer cuadrados ( ThisIndex ). Valor =
iValue = 0 End If Si cuadrados ( i ). nCol = Cuadrados ( ThisIndex ). nCol Luego
cuadrados ( i ). Possibles ( iValue ) = 0 End If Si cuadrados ( i ). NBox =
Cuadrados ( ThisIndex ). NBox Luego cuadrados ( i ). Possibles ( iValue ) = 0 End
If Next 'y aseg�rese de Possibles esta plaza se han establecido correctamente para
i = 1 Para ncSIZE cuadrados ( ThisIndex ). Possibles ( i ) = 0 Siguiente cuadrados
( ThisIndex ). Possibles ( iValue ) = 1 escuadra = True End Funci�n P�blica Funci�n
SetSquareRC ( iValue As Integer , IRow As Integer , iCol As Integer , opcional
IsGiven As Boolean ) As Boolean Valor de ajuste cuadrado "dado (fila, columna).
Opcionalmente, establecer la etiqueta dada. Dim Indice As Integer �ndice = getIndex
( IRow , iCol ) Cuadrados ( �ndice ). Teniendo en cuenta = IsGiven SetSquareRC =
escuadra ( iValue , �ndice ) End Function Public Function FillInResults () Dim rng
Como Range Dim IRow As Integer , iCol As Integer Dim iValue As Integer Dim �ndice
como conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) Si cuadrados ( �ndice ).
Teniendo en cuenta entonces 'Just formato para mostrar que era un hecho generador
de n�meros aleatorios ( IRow , iCol ). Interior . ColorIndex = 6 rng ( IRow ,
iCol ). Fuente . Negrita = verdadero cuadrados ElseIf ( �ndice ). Valor > 0 Luego
encontrado una soluci�n rng ( IRow , iCol ). Valor = Cuadrados ( �ndice ). rng
Valor ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = False End If Next Next End Funci�n P�blica ClearGrid () Dim rng Como
Range Dim IRow As Integer , iCol As Integer Dim iValue como Dim entero �ndice como
conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para iCol
= 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) rng ( IRow , iCol ) . Valor = ""
rng ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = Falso Siguiente End Function Public Function ReadInput () As Integer 0
"si el �ndice m�s bien de la plaza con el problema Dim rng Como Range Dim wkb Como
libro Dim IRow As Integer , iCol As Integer Dim iValue As Integer Set wkb =
ActiveWorkbook Set rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE iValue = Val ( rng . art�culo ( IRow , iCol )) Si iValue > 0
Luego, "tienda le da un valor en la matriz Si no SetSquareRC ( iValue , IRow , iCol
, cierto ) Entonces MsgBox "entrada no v�lida en (" y IRow y "," y iCol y ") "
Final Exit Function End If Si Siguiente ReadInput = IsDataOK () End Function
Funci�n P�blica InitPuzzle () 'Inicializar las Plazas de la matriz Dim IRow As
Integer , iCol As Integer Dim �ndice Como Dim entero i As Integer 'init todos los
valores por �ndice = 1 Para ncINDEXLEN cuadrados ( �ndice ). Teniendo en cuenta =
Falso cuadrados ( �ndice ). GuessLevel = 0 Cuadrados ( �ndice ). Valor = 0
Siguiente Para i = 1 Para ncGUESSEDMAX adivinado ( i ) = 0 Siguiente 'Set todos los
posibles para un para �ndice = 1 Para ncINDEXLEN Para i = 1 Para ncSIZE cuadrados (
�ndice ). Possibles ( i ) = 1 Siguiente 'Ajuste el nivel de adivinar mundial
mnGuessLevel = 0 mnDifficulty = 0 'Inicializar el n�mero de fila, columna y la caja
"para agilizar las b�squedas" (Estos se podr�a hacer con las constantes, pero esto
es m�s f�cil) 'fila almacenados columna x, base-1 Para iCol = 1 a 9 para IRow = 1 a
9 �ndice = getIndex ( IRow , iCol ) Cuadrados ( �ndice ). nRow = IRow cuadrados
( �ndice ). nCol = iCol Siguiente 'n�meros Set caja 1 .. 9' (hay sin duda un
algoritmo sencillo, pero esta Funci�n P�blica getIndex ( IRow As Integer , iCol As
Integer ) As Integer dado "valor de retorno (IRow, iCol) del �ndice (1 .. 81)
getIndex = ( IRow - 1 ) * ncSIZE + iCol End Function Public Function GetRow
( iIndex As Integer ) As Integer GetRow = (( iIndex - 1 ) \ ncSIZE ) + 1 End
Function Public Function GetCol ( iIndex As Integer ) As Integer GetCol = (( iIndex
- 1 ) Mod ncSIZE ) + 1 End Function Public Function GetBox ( iIndex As Integer ) As
Integer Dim nRow As Integer , nCol como Dim entero nBand como Dim entero nStack As
Integer nRow = GetRow ( iIndex ) nCol = GetCol ( iIndex ) nBand = ( nRow - 1 ) \ 3
+ 1 nStack = ( nCol - 1 ) \ 3 + 1 GetBox = ( nBand - 1 ) * 3 + nStack End Function
Funci�n P�blica InThisRow ( TheValue As Integer , TheIndex As Integer ) As Boolean
Dim �ndice Como Dim entero nRow como Por End If End If Next End Function Public
Function InThisCol ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero nCol como Por End If End If Next End Function Public
Function InThisBox ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero NBox como Por End If End If Next End Function Sub
Button1_Click () DoPuzzle End Sub Sub Button3_Click () ClearGrid End Sub

Option Explicit 'Este c�digo intenta solucionar los problemas de 9x9 Su Doku.'
'Copyright (C) 2004 David Ireland', 'Este programa es software libre, puede
redistribuirlo y / o "modificado bajo los t�rminos de la Licencia P�blica General
de GNU" publicada por la Free Software Foundation, versi�n 2 'de la Licencia, o (a
su elecci�n) cualquier versi�n posterior. "" Este programa se distribuye con la
esperanza de que sea �til, "pero SIN NINGUNA GARANT�A, incluso sin la garant�a
impl�cita de 'o IDONEIDAD PARA UN PROP�SITO PARTICULAR. Ver la "GNU General Public
License para m�s detalles." "Usted deber�a haber recibido una copia de la GNU
General Public License" junto con este programa, si no, escriba a la Free Software
'Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, EE.UU..
<http://www.gnu.org/licenses/> '"Contacto: David Ireland, DI Management Services
Pty Ltd' <http://www.di-mgt.com.au> '<http://www. > di-mgt.com.au/contactmsg.php
'<http://www.cryptosys.net> Const ncSIZE As Integer = 9 Const ncINDEXLEN As Integer
= ncSIZE * ncSIZE Tipo Valor udtSQUARE As Integer '0 = no establecido, de lo
contrario valor 1 .. 9 Possibles ( ncSIZE ) As Integer '1 = 0 es posible, = no es
posible GuessLevel As Integer '0 = firme, m�s nivel de adivinar 1,2,3, ... Teniendo
en cuenta As Boolean True 'si se le da en el problema nRow As Integer 'Para la
b�squeda r�pida. Establecidos por InitPuzzle nCol As Integer '�dem NBox As Integer
'�dem End Type 'matriz Almacenar en un array lineal, una basada en lo ignore (0).
P�blicas cuadrados ( ncSIZE * ncSIZE ) Como udtSQUARE "A nivel mundial en la que
estamos adivinar (0 = empresa) privada mnGuessLevel As Integer '�ndices de
conjeturas que ya hemos tratado (esperemos que no demasiados) Const ncGUESSEDMAX As
Integer = 12 'n�mero arbitrario privado adivinado ( ncGUESSEDMAX ) As Integer
'Dificultad P�blica mnDifficulty Como la Funci�n P�blica entero DoPuzzle () Dim
BadIndex As Integer 'Crear la matriz de llamadas InitPuzzle 'Leer los datos en la
matriz BadIndex = ReadInput () Si BadIndex <> 0 Entonces MsgBox "los datos de
entrada no es v�lida. Problema con (" y GetRow ( BadIndex ) y "", y GetCol
( BadIndex ) y ")" , vbCritical End Function Si la salida de depuraci�n . Imprimir
"En el comienzo, valores perdidos =" y MissingValues ??() 'Intenta resolver sin una
conjetura llamada TrySolve Si MissingValues ??()> 0 Luego, "Ahora vamos a tener de
adivinar, posiblemente de forma recursiva llamada TryGuess End If Si
MissingValues ??() = 0 Entonces MsgBox "Hemos encontrado una soluci�n. nivel de
dificultad = problema" y FillInResults mnDifficulty m�s si vbOK = MsgBox ( "Lo
siento, no pod�a resolver. �Quieres que el valores conocidos llenado? " ,
vbOKCancel ) Luego FillInResults End If End If End Function Funci�n P�blica
TryGuess () As Boolean 'Trate de adivinar. Funci�n recursiva. Dim GuessIndex como
Dim entero i As Integer Dim nValue As Integer Dim nMaxGuesses As Integer Dim
GuessPossibles ( ncSIZE ) As Integer Dim TrialIndex As Integer TryGuess = Falso
mnDifficulty = mnDifficulty + 1 'Incrementa el nivel actual de adivinar lo que
puede dar marcha atr�s si fuese necesario mnGuessLevel = mnGuessLevel + una
depuraci�n . Imprimir "adivinar NIVEL =" y mnGuessLevel "Todo lo que hacemos a
partir de ahora ser� provisional ..." Verificaci�n del l�mite de lo que no duran
para siempre Si mnGuessLevel > ncGUESSEDMAX Entonces MsgBox "Intent� adivinar
demasiado!" , vbExclamation Final Exit Function Si 'Elija un cuadrado con las
tarifas m�s posibilidades # ??�con exclusi�n de cualquier conjeturas antes
GuessIndex = FindMinPossibles () "Recuerden por lo que no vuelva a intentarlo
adivinado ( mnGuessLevel ) = GuessIndex nMaxGuesses = CountPossibles ( GuessIndex )
'recordar los detalles de esta plaza central para i = 1 Para ncSIZE GuessPossibles
( i ) = Cuadrados ( GuessIndex ). Possibles ( i ) A continuaci�n de depuraci�n .
Imprimir "Adivinar por cuadrados (" y GetRow ( GuessIndex ) y "", y GetCol
( GuessIndex ) y ")" depuraci�n . nMaxGuesses de impresi�n y "valores posibles"
'Rellenar con la conjetura siguiente, el trabajo a trav�s de todos los posibles
para TrialIndex = 1 Para nMaxGuesses nValue = TheNthPossible ( GuessIndex ,
TrialIndex ) de depuraci�n . Imprimir "valor = Adivinar" y nValue Si nValue < = 0
Entonces MsgBox "Run de conjeturas" Final Exit Function Si la llamada escuadra
( nValue , GuessIndex ) Si TrySolve () A continuaci�n, "Hemos terminado la salida
para ventas de depuraci�n . Imprimir "Supongo que fracas�". Llame UndoGuess
( mnGuessLevel ) de depuraci�n . Imprimir "Despu�s de UndoGuess: Los valores
perdidos =" y MissingValues ??() End If Next depuraci�n . Imprimir ". END TryGuess
valores perdidos =" y MissingValues ??() 'Si no estamos all� todav�a, que pruebe
con otro (recursiva) Supongo que en el siguiente nivel si MissingValues ??()> 0
Luego de llamadas TryGuess End If End Function Funci�n P�blica UndoGuess ( ByVal
ThisLevel As Integer ) 'Deshacer todas las conjeturas en este "nivel y rehacer
todos los posibles, porque est�n equivocados Dim �ndice Como Dim entero i As
Integer Dim nOldLevel As Integer Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). GuessLevel = ThisLevel Luego cuadrados ( �ndice ). Valor = 0 End If
Para i = 1 Para ncSIZE cuadrados ( �ndice ). Possibles ( i ) = 1 Siguiente "Para
restablecer todos los posibles, el uso escuadra para restablecer las plazas
conocidas", pero supongo que cambiar temporalmente el nivel de cero, mientras lo
hacemos nOldLevel = mnGuessLevel Si Siguiente mnGuessLevel = depuraci�n
nOldLevel . Imprimir "Supongo que a nivel de deshecho" y mnGuessLevel Funci�n
P�blica fin TrySolve () As Boolean 'tratar de resolver con una respuesta
definitiva' Devuelve True si resuelve Dim iRound como Dim entero hecho As Boolean
Dim nPrevious As Integer mnDifficulty = mnDifficulty + 1 iRound = 0 nPrevious = 0
hacer = Falso Hacer hasta hace o nPrevious = MissingValues ??() "Recuerden el
conteo previo para que podamos dejar de nPrevious = MissingValues ??() 'Este va
primero puede resolver los problemas m�s simples absoluta Hacer mientras
SetKnownValues ??( ) iRound = iRound + una depuraci�n . Imprimir "Completado todo"
y iRound y ". Los valores perdidos =" y MissingValues ??() bucle si
MissingValues ??() = 0 Luego de depuraci�n . Imprimir "Resuelto en Primera Go!"
hace = salida verdadera acaban Si "Ahora esforzarse m�s mnDifficulty = mnDifficulty
+ 1 Hacer mientras TryEachBox () de depuraci�n . Imprimir "Trat� de cada caja. Los
valores perdidos =" y MissingValues ??() Hacer mientras SetKnownValues ??() iRound
= iRound + una depuraci�n . Imprimir "Completado todo" y iRound y ". Valores
perdidos =" y MissingValues ??() Loop Si MissingValues ??() = 0 Luego hacer =
salida verdadera Do End If Do Mientras TryEachRow () de depuraci�n . Imprimir
"Trat� de cada fila. Los valores perdidos =" y MissingValues ??() No Si
SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir "Completado todo" y
iRound y ". Los valores perdidos =" y MissingValues ??() Loop Si MissingValues ??()
= 0 Luego hacer = salida verdadera Do End If Do Mientras TryEachCol () Depuraci�n .
Imprimir "Trat� de cada col. Los valores perdidos =" y MissingValues ??() Hacer
mientras SetKnownValues ??() iRound = iRound + una depuraci�n . Imprimir
"Completado todo" y iRound y ". Valores perdidos =" y MissingValues ??() Loop Si
MissingValues ??( ) = 0 Luego hacer = salida verdadera Do End If bucle "Hasta hace
TrySolve = ( MissingValues ??() = 0 ) End Function Funci�n P�blica AlreadyGuessed (
ThisIndex As Integer ) As Boolean 'Devuelve True si ya hemos adivinado el valor de
este �ndice "a un nivel inferior (es decir, mnGuessLevel ya se ha incrementado) Dim
i As Integer Para i = 1 Para mnGuessLevel - 1 Si adivinado ( i ) = ThisIndex Luego
AlreadyGuessed = true Para Salir End If Next End Function Funci�n P�blica
FindMinPossibles () As Integer "m�s bajo �ndice de devoluciones a una plaza sin
resolver por el n � posibilidades" con exclusi�n de cualquier conjeturas antes en
los niveles inferiores Dim Indice As Integer Dim nMin As Integer Dim nMinIndex As
Integer nMin = ncSIZE + 1 Por �ndice = 1 Para ncINDEXLEN Si cuadrados ( �ndice ).
Valor = 0 Y CountPossibles ( �ndice ) < nMin Entonces Si no AlreadyGuessed ( �ndice
) Luego nMin = CountPossibles ( �ndice ) nMinIndex = �ndice End If End If Next
FindMinPossibles = nMinIndex End Function Funci�n P�blica TryEachBox () As Boolean
'Trate a todos los candidatos de cada caja, hasta que nos encontramos con algo
nuevo: "Si encontramos una nueva, detener, ajustar el valor y el retorno True 'Si
no hay suerte, devuelva False Dim iBox As Integer Dim iValue As Integer Dim n As
Integer Dim nFoundAt As Integer TryEachBox = False para iBox = 1 A ncSIZE Para
iValue = 1 Para ncSIZE n = PossiblesInBox ( iValue , iBox , nFoundAt ) Si n = 1 A
continuaci�n, "Marque esta no est� configurado Si cuadrados ( nFoundAt ). Valor = 0
A continuaci�n, "�Hurra! Hemos resuelto esta plaza llamada escuadra ( iValue ,
nFoundAt ) "No vayamos m�s lejos ahora TryEachBox = True End If End Exit Function
Si Siguiente End Function Public Function TryEachRow () As Boolean 'Trate a todos
los candidatos para cada fila hasta que encontremos algo nueva 'Si encontramos una
nueva, detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva
False Dim IRow As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As
Integer TryEachRow = False para IRow = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n
= PossiblesInRow ( iValue , IRow , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachRow = True End If End Exit Function Si Siguiente End Function
Public Function TryEachCol () As Boolean 'Trate a todos los candidatos
para cada columna hasta que encontremos algo nueva 'Si encontramos una nueva,
detener, ajustar el valor y el retorno True' Si no hay suerte, devuelva False Dim
iCol As Integer Dim iValue As Integer Dim n As Integer Dim nFoundAt As Integer
TryEachCol = False para iCol = 1 Para ncSIZE Para iValue = 1 Para ncSIZE n =
PossiblesInCol ( iValue , iCol , nFoundAt ) Si n = 1 A continuaci�n, "Marque esta
no est� configurado Si cuadrados ( nFoundAt ). Valor = 0 A continuaci�n, "�Hurra!
Hemos resuelto esta plaza llamada escuadra ( iValue , nFoundAt ) "No vayamos m�s
lejos ahora TryEachCol = True End Exit Function End If Next Si Final de la Funci�n
P�blica Funci�n PossiblesInBox ( ThisValue As Integer , NBox As Integer , ByRef
FoundAt As Integer ) ' Devoluciones no de los posibles para este valor en esta
"caja y se pone FoundAt a ser el �ndice, donde la �ltima vez que encontr� una
posible este valor Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt
= �ndice End If End If Next PossiblesInBox = n End Function Funci�n P�blica
PossiblesInRow ( ThisValue As Integer , nRow As Integer , ByRef FoundAt As
Integer ) 'Devuelve no de los posibles para este valor en esta l�nea " y establece
FoundAt a ser el �ndice, donde la �ltima vez que encontr� una posible este valor
Dim Indice As Integer Dim n como > 0 entonces n = n + 1 FoundAt = �ndice End If
End If Next PossiblesInRow = n End Function Public Function PossiblesInCol
( ThisValue As Integer , nCol As Integer , ByRef FoundAt As Integer ) 'Devuelve no
de los posibles para este valor en este col' y establece FoundAt a ser el �ndice,
donde la �ltima vez que encontr� una posible este valor Dim Indice As Integer Dim n
como > 0 entonces n = n + 1 FoundAt = �ndice End If End If Next PossiblesInCol = n
End Function Public Function MissingValues ??() As Integer no el n�mero
"Devoluciones de escuadras. Si es cero, tenemos una soluci�n completa. Dim Indice
As Integer Dim n As Integer n = 0 Para Indice = 1 Para ncINDEXLEN Si cuadrados
( �ndice ). Valor = 0 Luego, n = n + 1 End If Next MissingValues ??= n End Function
Funci�n P�blica SetKnownValues ??() As Boolean 'Comprueba si simple eliminaci�n de
los posibles nos da ninguna soluci�n' Devuelve True si se hace un cambio o falso si
no hay cambios en este paso Dim Indice As Integer Dim iValue As Integer Dim
bChanged As Boolean bChanged = False �ndice = 1 Para ncINDEXLEN Si CountPossibles (
�ndice ) = 1 Y cuadrados ( �ndice ). Valor = 0 A continuaci�n, 'encontrado otra
respuesta iValue = ThePossible ( �ndice ) de depuraci�n . Imprimir "Se ha
encontrado de valor (" y GetRow ( �ndice ) y "", y GetCol ( �ndice de ) y ") =" y
iValue 'Establecer el valor (y eliminar los posibles m�s) Llame a escuadra ( iValue
, �ndice ) bChanged = True End If Next depuraci�n . Imprimir "SetKnownValues:" y
SiInm ( bChanged , "encontrado m�s ..." , "NO HAY CAMBIOS esta ronda" )
SetKnownValues ??= bChanged End Function Public Function CountPossibles ( �ndice de
As Integer ) As Integer 'N�mero no de los valores que son posibles para esta plaza:
"Si, tenemos la" soluci�n Si es cero, tenemos un error Dim i As Integer Dim n As
Integer n = 0 para i = 1 Para ncSIZE n = n + cuadrados ( �ndice ). Possibles ( i )
Siguiente CountPossibles = n End Function Funci�n P�blica ThePossible ( �ndice de
As Integer ) As Integer 'Se supone s�lo un posible valor Dim i As Integer Para i =
1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 Entonces ThePossible = i
Exit For End If Next End Funci�n P�blica Funci�n TheNthPossible ( �ndice de As
Integer , n_th As Integer ) As Integer ' encuentra el valor n posible para esta
plaza (base 1) Dim i As Integer Dim nValue As Integer Dim n As Integer n = n_th
Para i = 1 Para ncSIZE Si cuadrados ( �ndice ). Possibles ( i ) = 1 entonces n = n
- 1 Si n = 0 Luego nValue = i Exit For End If End If Next TheNthPossible = nValue
End Function Funci�n P�blica IsDataOK () As Integer 'Devuelve cero si los datos son
correctos, el �ndice m�s del primer error Dim Indice As Integer IsDataOK = 0 '
inocente hasta que se demuestre < = 0 Luego IsDataOK = �ndice de Exit For End If
Next End Function Public Function escuadra ( iValue As Integer , ThisIndex As
Integer ) As Boolean 'Establecer el valor plaza y eliminar todos los posibles en la
misma fila, columna y caja de Dim i As Integer cuadrados ( ThisIndex ). Valor =
iValue = 0 End If Si cuadrados ( i ). nCol = Cuadrados ( ThisIndex ). nCol Luego
cuadrados ( i ). Possibles ( iValue ) = 0 End If Si cuadrados ( i ). NBox =
Cuadrados ( ThisIndex ). NBox Luego cuadrados ( i ). Possibles ( iValue ) = 0 End
If Next 'y aseg�rese de Possibles esta plaza se han establecido correctamente para
i = 1 Para ncSIZE cuadrados ( ThisIndex ). Possibles ( i ) = 0 Siguiente cuadrados
( ThisIndex ). Possibles ( iValue ) = 1 escuadra = True End Funci�n P�blica Funci�n
SetSquareRC ( iValue As Integer , IRow As Integer , iCol As Integer , opcional
IsGiven As Boolean ) As Boolean Valor de ajuste cuadrado "dado (fila, columna).
Opcionalmente, establecer la etiqueta dada. Dim Indice As Integer �ndice = getIndex
( IRow , iCol ) Cuadrados ( �ndice ). Teniendo en cuenta = IsGiven SetSquareRC =
escuadra ( iValue , �ndice ) End Function Public Function FillInResults () Dim rng
Como Range Dim IRow As Integer , iCol As Integer Dim iValue As Integer Dim �ndice
como conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) Si cuadrados ( �ndice ).
Teniendo en cuenta entonces 'Just formato para mostrar que era un hecho generador
de n�meros aleatorios ( IRow , iCol ). Interior . ColorIndex = 6 rng ( IRow ,
iCol ). Fuente . Negrita = verdadero cuadrados ElseIf ( �ndice ). Valor > 0 Luego
encontrado una soluci�n rng ( IRow , iCol ). Valor = Cuadrados ( �ndice ). rng
Valor ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = False End If Next Next End Funci�n P�blica ClearGrid () Dim rng Como
Range Dim IRow As Integer , iCol As Integer Dim iValue como Dim entero �ndice como
conjunto entero rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para iCol
= 1 Para ncSIZE �ndice = getIndex ( IRow , iCol ) rng ( IRow , iCol ) . Valor = ""
rng ( IRow , iCol ). Interior . ColorIndex = xlNone rng ( IRow , iCol ). Fuente .
Negrita = Falso Siguiente End Function Public Function ReadInput () As Integer 0
"si el �ndice m�s bien de la plaza con el problema Dim rng Como Range Dim wkb Como
libro Dim IRow As Integer , iCol As Integer Dim iValue As Integer Set wkb =
ActiveWorkbook Set rng = Range ( "Rompecabezas" ) Para IRow = 1 Para ncSIZE Para
iCol = 1 Para ncSIZE iValue = Val ( rng . art�culo ( IRow , iCol )) Si iValue > 0
Luego, "tienda le da un valor en la matriz Si no SetSquareRC ( iValue , IRow , iCol
, cierto ) Entonces MsgBox "entrada no v�lida en (" y IRow y "," y iCol y ") "
Final Exit Function End If Si Siguiente ReadInput = IsDataOK () End Function
Funci�n P�blica InitPuzzle () 'Inicializar las Plazas de la matriz Dim IRow As
Integer , iCol As Integer Dim �ndice Como Dim entero i As Integer 'init todos los
valores por �ndice = 1 Para ncINDEXLEN cuadrados ( �ndice ). Teniendo en cuenta =
Falso cuadrados ( �ndice ). GuessLevel = 0 Cuadrados ( �ndice ). Valor = 0
Siguiente Para i = 1 Para ncGUESSEDMAX adivinado ( i ) = 0 Siguiente 'Set todos los
posibles para un para �ndice = 1 Para ncINDEXLEN Para i = 1 Para ncSIZE cuadrados (
�ndice ). Possibles ( i ) = 1 Siguiente 'Ajuste el nivel de adivinar mundial
mnGuessLevel = 0 mnDifficulty = 0 'Inicializar el n�mero de fila, columna y la caja
"para agilizar las b�squedas" (Estos se podr�a hacer con las constantes, pero esto
es m�s f�cil) 'fila almacenados columna x, base-1 Para iCol = 1 a 9 para IRow = 1 a
9 �ndice = getIndex ( IRow , iCol ) Cuadrados ( �ndice ). nRow = IRow cuadrados
( �ndice ). nCol = iCol Siguiente 'n�meros Set caja 1 .. 9' (hay sin duda un
algoritmo sencillo, pero esta Funci�n P�blica getIndex ( IRow As Integer , iCol As
Integer ) As Integer dado "valor de retorno (IRow, iCol) del �ndice (1 .. 81)
getIndex = ( IRow - 1 ) * ncSIZE + iCol End Function Public Function GetRow
( iIndex As Integer ) As Integer GetRow = (( iIndex - 1 ) \ ncSIZE ) + 1 End
Function Public Function GetCol ( iIndex As Integer ) As Integer GetCol = (( iIndex
- 1 ) Mod ncSIZE ) + 1 End Function Public Function GetBox ( iIndex As Integer ) As
Integer Dim nRow As Integer , nCol como Dim entero nBand como Dim entero nStack As
Integer nRow = GetRow ( iIndex ) nCol = GetCol ( iIndex ) nBand = ( nRow - 1 ) \ 3
+ 1 nStack = ( nCol - 1 ) \ 3 + 1 GetBox = ( nBand - 1 ) * 3 + nStack End Function
Funci�n P�blica InThisRow ( TheValue As Integer , TheIndex As Integer ) As Boolean
Dim �ndice Como Dim entero nRow como Por End If End If Next End Function Public
Function InThisCol ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero nCol como Por End If End If Next End Function Public
Function InThisBox ( TheValue As Integer , TheIndex As Integer ) Dim como Boolean
�ndice Como Dim entero NBox como Por End If End If Next End Function Sub
Button1_Click () DoPuzzle End Sub Sub Button3_Click () ClearGrid End Sub

Vous aimerez peut-être aussi