elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


  Mostrar Temas
Páginas: 1 2 3 4 [5] 6 7 8 9 10 11 12 13 14 15 16 17
41  Programación / Programación Visual Basic / vb6 es tonto en: 2 Octubre 2011, 01:08 am
Hola chicos, bueno a raíz de una discusión con la profesora de programación he investigado sobre los Ifs de vb6... :rolleyes:

En esta situación:
Código
  1. If A = True Or B = False Then
Lo lógico sería que al leer A=True no comprobara Lo siguiente puesto que la condición se cumpliría de todas formas. :)
Pero no, vb te comprueba TODO el If pase lo que pase en todos los casos. :¬¬

Aquí un código que lo demuestra:

Código
  1. Option Explicit
  2.  
  3. Private Function OrTest(ByVal bReturn As Boolean) As Boolean
  4.    '// Imprimo un texto para saber que he pasado por la función.
  5.    Debug.Print Time$, "Función con el argumento " & bReturn & " llamada."
  6.    OrTest = bReturn
  7. End Function
  8.  
  9. Private Sub Form_Load()
  10.  
  11.    '// Aquí lo logico sería comprobar las dos ya que
  12.    '// si la primera no es true, lo puede ser la segunda.
  13.    If OrTest(False) Or OrTest(False) Then
  14.        '// Nothing
  15.    End If
  16.  
  17.    Debug.Print String$(75, "=")
  18.  
  19.    '// Lo lógico sería que se saltase la segunda función puesto
  20.    '// que la primera es true, pero no, nuestro querido vb
  21.    '// comprueba igual...
  22.    If OrTest(True) Or OrTest(False) Then
  23.        '// Nothing
  24.    End If
  25. End Sub
  26.  

Retorno:
Código:
00:27:48      Función con el argumento Falso llamada.
00:27:48      Función con el argumento Falso llamada.
===========================================================================
00:27:48      Función con el argumento Verdadero llamada.
00:27:48      Función con el argumento Falso llamada.


Sé que alguno dirá: ¿y a mí qué más me da si el resultado es el mismo?
Bueno, pues imagina que tienes un If tal que así:

Código
  1. If Calculo(1) Or Calculo(2) Or Calculo(3) Or Calculo(4) Or Calculo(5) Then
  2.    '...
  3. End If
La función Calculo() es un algoritmo complejo y tarda 1 segundo de media.
Si fuera otro lenguaje de programación si Calculo(1) es true se saltaría los demás, pero nuestro querido vb6 llamará a todas las demás funciones perdiendo tiempo innecesariamente... :-\ Pasando de 1 seg a 5 en este caso.
La alternativa que propongo en estos casos es (no son agradables a la vista, aviso :xD) :

Sustituir esto:
Código
  1.    If A(324) = 45 Or B(12) = 2 Or B(4563) = 56 Then
  2.        Call DoIt
  3.    End If

Por esto:
Código
  1.    If A(324) = 45 Then
  2.        Call DoIt
  3.    ElseIf B(12)=2 Then
  4.        Call DoIt
  5.    ElseIf B(4563) = 56 Then
  6.       Call DoIt
  7.    End If

Esto:
Código
  1.    If A(324) = 45 And B(12) = 2 And B(4563) = 56 Then
  2.        '...
  3.    End If

Por esto:
Código
  1.    If A(324) = 45 Then
  2.        If B(12) = 2 Then
  3.            If B(4563) = 56 Then
  4.                '...
  5.            End If
  6.        End If
  7.   End If
Con esto no quiero decir que lo hagáis así de normal, sólo cuando necesitemos velocidad.
Hice estas pruebas a ver si algún lenguaje más era tonto, pero por ahora sólo es vb6.
Si alguien sabe de otro hacedmelo saber, me interesa mucho.
Dedico este articulo a Karcrack, BlackZero, TheSwash y raul338 por orientarme y ayudarme con los test.

VB.NET tiene una expresion para evitar esto:
Código:
Short-Circuiting Logical Operations http://msdn.microsoft.com/en-us/library/wz3k228a.aspx

Más info:
Código:
http://en.wikipedia.org/wiki/Short-circuit_evaluation

Espero que al menos a alguien le sirva todo esto. :)

DoEvents! :P
42  Programación / Programación Visual Basic / [RETO] Palabras pronunciables en: 29 Septiembre 2011, 11:01 am
Bueno, pues la idea es generar una funcion donde ingresemos la longitud de la cadena y te generara una palabra pronunciable.
Por supuesto deben estar contemplados las combinaciones entre dos consonantes.

Ejemplos falsos:
Código:
asdoijs
ouughjt
esrah
wilsohc

Ejemplos verdaderos:
Código:
hola
chema
llama
nikos
clueim
tefral

Sin límite de entrega, todo vale... :)

DoEvents! :P
43  Programación / Programación Visual Basic / Verificar celdas... en: 23 Septiembre 2011, 18:58 pm
Hola buenas, pido vuestra ayuda:
Hay un juego del estilo al biotronic, y al igual que el bioSolver necesito hacer una plantilla que descifre los cuadros que hay debajo.
Para ello pensé hacer 4 GetPixel() por cada celda, si esos cuatro puntos son de un color similar, podré deducir el color de la celda.
El problema es que hay figuras diferentes que no sé como validar:
Este:

O podría confundir estos dos:


¿Alguna idea? ¿Alguna forma mejor de hacerlo?
Tened en cuenta que debe ser algo rápido, se debe actualizar cada 500ms o así... ::)
Igual con el CheatEngine se podría hacer algo, pero a todo el mundo que pregunto me llama loco.
Gracias. :D

DoEvents! :P
44  Programación / Programación Visual Basic / [RETO] Sudoku en: 21 Septiembre 2011, 20:50 pm
Un reto dificilillo...
Código:
Function SolveSudoku_raul338(s() As Byte) As Byte()
Se introduce una matriz bidimensional de 9x9. Los huecos serán "0"
Info
Código:
http://es.wikipedia.org/wiki/Sudoku
Vale todo, el más rápido gana.

DoEvents! :P
45  Programación / PHP / [PHP] Problema verificación Twitter en: 16 Septiembre 2011, 13:46 pm
Perdón... ;D mover esto al foro de PHP... :rolleyes:

Hola, vi por ahí un articulo:
http://blog.timersys.com/tutoriales/actualizar-twitter-a-traves-de-php-y-oauth/
Sigo todos los pasos... pero me tira error...

¿Sabéis qué hago mal?
Puede ser que hallan actualizado la librería twitteroauth.php y ahora haya alguna incoherencia...
Consulté más ejemplos y me tira el mismo error. (Ambos usaban la librería antes citada)
Aún soy n00b en esto, así que gracias por la ayuda. :)

DoEvents! :P
46  Media / Diseño Gráfico / Efecto "comic" en fotos en: 7 Agosto 2011, 02:37 am
Hola chicos, vengo con una duda muy concreta.
¿Cómo podría conseguir el efecto que tienen las fotos de esta web?
Código:
http://photodmn.com/
¿Se podría hacer con el GIMP también?

Muchas gracias ;D
47  Foros Generales / Foro Libre / Se acerca... ya está ahí... en: 30 Mayo 2011, 18:11 pm
... la P.A.U. (Prueba de Acceso Universitaria) o Selectividad o como la queráis llamar. :-(
Quedan sólo dos días, abro este post para saber si alguien más se va a examinar en España y cómo lleva la materia. :)


DoEvents! :P
48  Programación / Programación Visual Basic / [SRC] LoadRndNumericArray en: 27 Mayo 2011, 20:14 pm
Bueno, cómo ahora está de moda los numeros aleatorios encontré un hueco entre mis estudios y hice esto.
Soporta divrersos tipos de arrays...(Long, Byte, Integer...).
Uso la funcion de BlackZer0x :
http://goo.gl/RG4Bx
Tuve que cambiar un par de cosas nada más para adaptarlo.

Función:
Código
  1. Option Explicit
  2. '======================================================================
  3. ' º Function  : LoadRndNumericArray
  4. ' º Author    : Psyke1
  5. ' º Country   : Spain
  6. ' º Mail      : vbpsyke1@mixmail.com
  7. ' º Date      : 27/05/2011
  8. ' º Twitter   : http://twitter.com/#!/PsYkE1
  9. ' º Dedicated : BlackZer0x
  10. ' º Requirements : http://goo.gl/vgbtQ || http://goo.gl/BAPXx
  11. ' º Recommended Websites :
  12. '       http://foro.h-sec.org
  13. '       http://www.frogcheat.com.ar
  14. '       http://InfrAngeluX.Sytes.Net
  15. '======================================================================
  16. Private Declare Sub RtlMoveMemory Lib "kernel32.dll" (ByVal Destination&, ByVal Source&, ByVal Length&)
  17.  
  18. Public Static Function LoadRndNumericArray(lngMin&, lngMax&, varOutPutArr, Optional varExceptionArr) As Boolean
  19. Dim lngTotal&, lngFinalArr&(), lngRndIndex&, Q&, C&
  20.    If IsArray(varOutPutArr) Then
  21.        If lngMin < lngMax Then
  22.            lngTotal = lngMax - lngMin
  23.            C = 0
  24.  
  25.            If Not IsMissing(varExceptionArr) And IsArray(varExceptionArr) Then
  26.                Start_QuickSort varExceptionArr '// With little mod.
  27.  
  28.                lngTotal = lngTotal - (UBound(varExceptionArr) - LBound(varExceptionArr) + 1)
  29.                ReDim lngFinalArr&(0 To lngTotal)
  30.  
  31.                '// Fix repetitions and numbers out of range.
  32.                For Q = lngMin To lngMax
  33.                    If IsInArray(varExceptionArr, Q, , , , True) = -1 Then
  34.                        lngFinalArr(C) = Q
  35.                        C = C + 1
  36.                    End If
  37.                Next Q
  38.            Else
  39.                ReDim lngFinalArr&(0 To lngTotal)
  40.  
  41.                For Q = lngMin To lngMax
  42.                    lngFinalArr(C) = Q
  43.                    C = C + 1
  44.                Next Q
  45.            End If
  46.  
  47.            ReDim varOutPutArr(0 To lngTotal)
  48.            Randomize Timer
  49.  
  50.            For Q = 0 To lngTotal
  51.                lngRndIndex = Rnd * lngTotal
  52.                varOutPutArr(Q) = lngFinalArr(lngRndIndex)
  53.  
  54.                RtlMoveMemory VarPtr(lngFinalArr(lngRndIndex)), VarPtr(lngFinalArr(lngRndIndex + 1)), (lngTotal - lngRndIndex) * &H4
  55.                lngTotal = lngTotal - 1
  56.            Next Q
  57.  
  58.            LoadRndNumericArray = True
  59.        End If
  60.    End If
  61. End Function

Ejemplo:
Código
  1. Option Explicit
  2. Private Declare Sub RtlMoveMemory Lib "kernel32.dll" (ByVal Destination&, ByVal Source&, ByVal Length&)
  3.  
  4. Enum EnuListOrder
  5.    AcendetOrder = 0
  6.    DecendentOrder = 1
  7. End Enum
  8.  
  9. Public Static Function LoadRndNumericArray(lngMin&, lngMax&, varOutPutArr, Optional varExceptionArr) As Boolean
  10. Dim lngTotal&, lngFinalArr&(), lngRndIndex&, Q&, C&
  11.    If IsArray(varOutPutArr) Then
  12.        If lngMin < lngMax Then
  13.            lngTotal = lngMax - lngMin
  14.            C = 0
  15.  
  16.            If Not IsMissing(varExceptionArr) And IsArray(varExceptionArr) Then
  17.                Start_QuickSort varExceptionArr
  18.  
  19.                lngTotal = lngTotal - (UBound(varExceptionArr) - LBound(varExceptionArr) + 1)
  20.                ReDim lngFinalArr&(0 To lngTotal)
  21.  
  22.                '// Fix repetitions and numbers out of range.
  23.                For Q = lngMin To lngMax
  24.                    If IsInArray(varExceptionArr, Q, , , , True) = -1 Then
  25.                        lngFinalArr(C) = Q
  26.                        C = C + 1
  27.                    End If
  28.                Next Q
  29.            Else
  30.                ReDim lngFinalArr&(0 To lngTotal)
  31.  
  32.                For Q = lngMin To lngMax
  33.                    lngFinalArr(C) = Q
  34.                    C = C + 1
  35.                Next Q
  36.            End If
  37.  
  38.            ReDim varOutPutArr(0 To lngTotal)
  39.            Randomize Timer
  40.  
  41.            For Q = 0 To lngTotal
  42.                lngRndIndex = Rnd * lngTotal
  43.                varOutPutArr(Q) = lngFinalArr(lngRndIndex)
  44.  
  45.                RtlMoveMemory VarPtr(lngFinalArr(lngRndIndex)), VarPtr(lngFinalArr(lngRndIndex + 1)), (lngTotal - lngRndIndex) * &H4
  46.                lngTotal = lngTotal - 1
  47.            Next Q
  48.  
  49.            LoadRndNumericArray = True
  50.        End If
  51.    End If
  52. End Function
  53.  
  54. '   /////////////////////////////////////////////////////////////
  55. '   // Autor Algoritmo: C.A.R. Hoare en 1960                   //
  56. '   // Autor:   BlackZeroX ( Ortega Avila Miguel Angel )       //
  57. '   //                                                         //
  58. '   // Web:     http://InfrAngeluX.Sytes.Net/                  //
  59. '   //                                                         //
  60. '   //    |-> Pueden Distribuir Este Codigo siempre y cuando   //
  61. '   // no se eliminen los creditos originales de este codigo   //
  62. '   // No importando que sea modificado/editado o engrandesido //
  63. '   // o achicado, si es en base a este codigo                 //
  64. '   /////////////////////////////////////////////////////////////
  65.  
  66. Private Sub AuxOrden(ByRef mArray, i As Long, j As Long, il As Long, jl As Long)
  67. Dim C                                       As String
  68. Dim c2                                      As Long
  69.    C = mArray(j)
  70.    mArray(j) = mArray(i)
  71.    mArray(i) = C
  72.    c2 = il
  73.    il = -jl
  74.    jl = -c2
  75. End Sub
  76.  
  77. Private Sub PreSort(ByRef mArray, lb As Long, ub As Long, k As Long, Optional Order As EnuListOrder = DecendentOrder)
  78. Dim i                                       As Long
  79. Dim j                                       As Long
  80. Dim il                                      As Long
  81. Dim jl                                      As Long
  82.    il = 0: jl = -1
  83.    i = lb: j = ub
  84.    While i < j
  85.        If Order = DecendentOrder Then
  86.            If IsNumeric(mArray(i)) And IsNumeric(mArray(j)) Then
  87.                If Val(mArray(i)) > Val(mArray(j)) Then
  88.                    Call AuxOrden(mArray(), i, j, il, jl)
  89.                End If
  90.            Else
  91.                If mArray(i) > mArray(j) Then
  92.                    Call AuxOrden(mArray(), i, j, il, jl)
  93.                End If
  94.            End If
  95.        Else
  96.            If IsNumeric(mArray(i)) And IsNumeric(mArray(j)) Then
  97.                If Val(mArray(i)) < Val(mArray(j)) Then
  98.                    Call AuxOrden(mArray(), i, j, il, jl)
  99.                End If
  100.            Else
  101.                If mArray(i) < mArray(j) Then
  102.                    Call AuxOrden(mArray(), i, j, il, jl)
  103.                End If
  104.            End If
  105.        End If
  106.        i = i + il
  107.        j = j + jl
  108.    Wend
  109.    k = i
  110. End Sub
  111.  
  112. Private Sub QSort(ByRef mArray, lb As Long, ub As Long, _
  113.                Optional Order As EnuListOrder = DecendentOrder)
  114. Dim k                                   As Long
  115.    If lb < ub Then
  116.        PreSort mArray, lb, ub, k, Order
  117.        Call QSort(mArray, lb, k - 1, Order)
  118.        Call QSort(mArray, k + 1, ub, Order)
  119.    End If
  120. End Sub
  121.  
  122. Public Sub Start_QuickSort(ByRef mArray, Optional Order As EnuListOrder = DecendentOrder)
  123.    QSort mArray, LBound(mArray), UBound(mArray), Order
  124. End Sub
  125.  
  126. '// by Psyke1
  127. Public Static Function IsInArray&(varArr, _
  128.                                  varValue, _
  129.                                  Optional lngStart&, _
  130.                                  Optional lngEnd&, _
  131.                                  Optional bolFindFirst As Boolean, _
  132.                                  Optional bolIsSorted As Boolean)
  133. Dim lngLB&, lngUB&, Q&, C&
  134.    If (IsArray(varArr) = True) And (IsArray(varValue) = False) Then
  135.        lngLB = LBound(varArr)
  136.        lngUB = UBound(varArr)
  137.  
  138.        If Not IsMissing(lngStart) Then
  139.           If (lngStart > lngLB) And (lngStart < lngUB) Then lngLB = lngStart
  140.        End If
  141.        If Not IsMissing(lngEnd) Then
  142.           If (lngEnd > lngLB) And (lngEnd < lngUB) Then lngUB = lngEnd
  143.        End If
  144.  
  145.        If bolIsSorted Then
  146.            If varArr(lngLB) = varValue Then
  147.                IsInArray = lngLB
  148.                Exit Function
  149.            ElseIf varArr(lngUB) = varValue Then
  150.                If bolFindFirst Then
  151.                    Do While (varArr(lngUB) = varArr(lngUB - 1)) And (Q > lngLB)
  152.                        lngUB = lngUB - 1
  153.                    Loop
  154.                End If
  155.  
  156.                IsInArray = lngUB
  157.                Exit Function
  158.            End If
  159.  
  160.            If lngUB - lngLB < 2 Then GoTo NotFound
  161.            If (varArr(lngLB) > varValue) Or (varArr(lngUB) < varValue) Then GoTo NotFound
  162.  
  163.            C = 0
  164.            Do
  165.                Q = (lngUB + lngLB) \ 2
  166.                If C = Q Then GoTo NotFound
  167.  
  168.                If varArr(Q) > varValue Then
  169.                    lngUB = Q
  170.                ElseIf varArr(Q) < varValue Then
  171.                    lngLB = Q
  172.                    C = lngLB
  173.                Else
  174.                    If bolFindFirst Then
  175.                        Do While (varArr(Q) = varArr(Q - 1)) And (Q > lngLB)
  176.                            Q = Q - 1
  177.                        Loop
  178.                    End If
  179.  
  180.                    IsInArray = Q
  181.                    Exit Function
  182.                End If
  183.            Loop
  184.        Else
  185.            For Q = lngLB To lngUB
  186.                If varArr(Q) = varValue Then
  187.                    IsInArray = Q
  188.                    Exit Function
  189.                End If
  190.            Next Q
  191.  
  192.            GoTo NotFound
  193.        End If
  194.    End If
  195. Exit Function
  196.  
  197. NotFound:
  198.    IsInArray = -1
  199. End Function
  200.  
  201. Private Sub Form_Load()
  202. Dim varItem, lngOut&(), intEx%(0 To 3)
  203.  
  204.    intEx(0) = -2
  205.    intEx(1) = 1
  206.    intEx(2) = 5
  207.    intEx(3) = 8
  208.  
  209.    Debug.Print String$(40, "="), Time$
  210.  
  211.    If LoadRndNumericArray(-5, 10, lngOut, intEx) Then
  212.        For Each varItem In lngOut
  213.            Debug.Print varItem
  214.        Next varItem
  215.    End If
  216. End Sub

Resultado:
Código:
========================================  20:10:55
 4
-4
 7
 3
 9
-1
-5
 0
 10
 2
 6
-3

Voy a seguir estudiando para la selectividad... :) Bye

DoEvents! :P

49  Programación / Programación Visual Basic / [Src] IsInArray en: 9 Mayo 2011, 14:24 pm
Bueno, aquí os dejo esta sencilla función. :)
Su finalidad es devolver el Index de un Item que se encuentre en un array (acepta todo tipo de Arrays : String, Double, Long...), con la opción de devolver el primero que se encuentre en el array y con los parámetros lngStart y lngEnd podemos establecer límites en nuestra búsqueda.  :D
Para ordenarlo aconsejo usar esta maravillosa función que hizo mi amigo BlackZer0x :
http://goo.gl/RG4Bx

Código
  1. Option Explicit
  2. '======================================================================
  3. ' º Function  : IsInArray
  4. ' º Author    : Psyke1
  5. ' º Country   : Spain
  6. ' º Mail      : vbpsyke1@mixmail.com
  7. ' º Date      : 09/05/2011
  8. ' º Twitter   : http://twitter.com/#!/PsYkE1
  9. ' º Dedicated : BlackZer0x
  10. ' º Reference : http://goo.gl/RDQhK
  11. ' º Recommended Websites :
  12. '       http://foro.h-sec.org
  13. '       http://www.frogcheat.com.ar
  14. '       http://InfrAngeluX.Sytes.Net
  15. '======================================================================
  16. Public Static Function IsInArray&(varArr, _
  17.                                  varValue, _
  18.                                  Optional lngStart&, _
  19.                                  Optional lngEnd&, _
  20.                                  Optional bolFindFirst As Boolean, _
  21.                                  Optional bolIsSorted As Boolean)
  22. Dim lngLB&, lngUB&, Q&, C&
  23.    If (IsArray(varArr) = True) And (IsArray(varValue) = False) Then
  24.        lngLB = LBound(varArr)
  25.        lngUB = UBound(varArr)
  26.  
  27.        If Not IsMissing(lngStart) Then
  28.           If (lngStart > lngLB) And (lngStart < lngUB) Then lngLB = lngStart
  29.        End If
  30.        If Not IsMissing(lngEnd) Then
  31.           If (lngEnd > lngLB) And (lngEnd < lngUB) Then lngUB = lngEnd
  32.        End If
  33.  
  34.        If bolIsSorted Then
  35.            If varArr(lngLB) = varValue Then
  36.                IsInArray = lngLB
  37.                Exit Function
  38.            ElseIf varArr(lngUB) = varValue Then
  39.                If bolFindFirst Then
  40.                    Do While (varArr(lngUB) = varArr(lngUB - 1)) And (Q > lngLB)
  41.                        lngUB = lngUB - 1
  42.                    Loop
  43.                End If
  44.  
  45.                IsInArray = lngUB
  46.                Exit Function
  47.            End If
  48.  
  49.            If lngUB - lngLB < 2 Then GoTo NotFound
  50.            If (varArr(lngLB) > varValue) Or (varArr(lngUB) < varValue) Then GoTo NotFound
  51.  
  52.            C = 0
  53.            Do
  54.                Q = (lngUB + lngLB) \ 2
  55.                If C = Q Then GoTo NotFound
  56.  
  57.                If varArr(Q) > varValue Then
  58.                    lngUB = Q
  59.                ElseIf varArr(Q) < varValue Then
  60.                    lngLB = Q
  61.                    C = lngLB
  62.                Else
  63.                    If bolFindFirst Then
  64.                        Do While (varArr(Q) = varArr(Q - 1)) And (Q > lngLB)
  65.                            Q = Q - 1
  66.                        Loop
  67.                    End If
  68.  
  69.                    IsInArray = Q
  70.                    Exit Function
  71.                End If
  72.            Loop
  73.        Else
  74.            For Q = lngLB To lngUB
  75.                If varArr(Q) = varValue Then
  76.                    IsInArray = Q
  77.                    Exit Function
  78.                End If
  79.            Next Q
  80.  
  81.            GoTo NotFound
  82.        End If
  83.    End If
  84. Exit Function
  85.  
  86. NotFound:
  87.    IsInArray = -1
  88. End Function

Un ejemplo:
Código
  1. Option Explicit
  2.  
  3. Private Const strLine$ = "------------------------------"
  4.  
  5. Private Sub Form_Load()
  6. Dim L&(60), S(), Q&
  7.  
  8.    For Q = 0 To 60
  9.        L(Q) = Q * 2
  10.    Next Q
  11.  
  12.    Debug.Print strLine$, Time$, strLine$
  13.    Debug.Print IsInArray(L, 15)                '---> -1
  14.    Debug.Print IsInArray(L, 40)                '--->  20
  15.    Debug.Print IsInArray(L, 85)                '---> -1
  16.    Debug.Print IsInArray(L, 100)               '--->  50
  17.  
  18.    S = Array("abba", "acero", "karcrack", "sereno", "silencio", "tonto", "tonto", "tonto", "tonto", "zalme")
  19.  
  20.    Debug.Print strLine$
  21.    Debug.Print IsInArray(S, "zalme")           '--->  9
  22.    Debug.Print IsInArray(S, "zalme", , 4)      '---> -1
  23.    Debug.Print IsInArray(S, "mesa")            '---> -1
  24.    Debug.Print IsInArray(S, "besos")           '---> -1
  25.    Debug.Print IsInArray(S, "karcrack")        '--->  2
  26.    Debug.Print IsInArray(S, "karcrack", 3)     '---> -1
  27.    Debug.Print IsInArray(S, "tonto")           '--->  6
  28.    Debug.Print IsInArray(S, "tonto", , , True) '--->  5
  29. End Sub

Retorna:
Código:
------------------------------            18:59:54      ------------------------------
-1
 20
-1
 50
------------------------------
 9
-1
-1
-1
 2
-1
 6
 5



Si necesitamos especial velocidad y lo queremos para un tipo de variable en concreto, sólo hay que modificar un par de cosas. ;)
Aquí un ejemplo para buscar en un array Long, comparado con el código de BlackZer0x ( http://goo.gl/RDQhK ) :
Código:
Option Explicit
'// Compilado sin la comprobación de límites en los arrays xP

Private Sub Form_Load()
Dim L&(6000), Q&, t As New CTiming, y&
    
    If App.LogMode = 0 Then End
    
    For Q = 0 To 6000
        L(Q) = Q * 2
    Next Q
    
    Me.AutoRedraw = True
    
    t.Reset
    For Q = 1 To 1000
        IsInArray L, 15
        IsInArray L, 40
        IsInArray L, 2001
        IsInArray L, 5020
        IsInArray L, 12000
    Next Q
    Me.Print "IsInArray", , t.sElapsed
    
    t.Reset
    For Q = 1 To 1000
        ExitsInArrayNR 15, L, y
        ExitsInArrayNR 40, L, y
        ExitsInArrayNR 2001, L, y
        ExitsInArrayNR 5020, L, y
        ExitsInArrayNR 12000, L, y
    Next Q
    Me.Print "ExitsInArrayNR", t.sElapsed
End Sub

'// by Psyke1
Public Static Function IsInArray&(lngArr&(), lngValue&, Optional lngStart&, Optional lngEnd&, Optional bolFindFirst As Boolean)
Dim lngLB&, lngUB&, lngItem&, Q&, C&
    lngLB = LBound(lngArr)
    lngUB = UBound(lngArr)
    
    If Not IsMissing(lngStart) Then
       If (lngStart > lngLB) And (lngStart < lngUB) Then lngLB = lngStart
    End If
    If Not IsMissing(lngEnd) Then
       If (lngEnd > lngLB) And (lngEnd < lngUB) Then lngUB = lngEnd
    End If
    
    If lngArr(lngLB) = lngValue Then
        IsInArray = lngLB
        Exit Function
    ElseIf lngArr(lngUB) = lngValue Then
        If bolFindFirst Then
            Do While (lngArr(lngUB) = lngArr(lngUB - 1)) And (Q > lngLB)
                lngUB = lngUB - 1
            Loop
        End If
        IsInArray = lngUB
        Exit Function
    End If
    
    If lngUB - lngLB < 2 Then GoTo NotFound
    If (lngArr(lngLB) > lngValue) Or (lngArr(lngUB) < lngValue) Then GoTo NotFound
    
    C = 0
    Do
        Q = (lngUB + lngLB) \ 2
        If C = Q Then GoTo NotFound

        If lngArr(Q) > lngValue Then
            lngUB = Q
        ElseIf lngArr(Q) < lngValue Then
            lngLB = Q
            C = lngLB
        Else
            If bolFindFirst Then
                Do While (lngArr(Q) = lngArr(Q - 1)) And (Q > lngLB)
                    Q = Q - 1
                Loop
            End If
            IsInArray = Q
            Exit Function
        End If
    Loop
Exit Function

NotFound:
    IsInArray = -1
End Function

'// by BlackZer0x
Public Function ExitsInArrayNR(ByRef vValue As Long, ByRef vBuff() As Long, ByRef p As Long) As Boolean
Dim lng_lb                      As Long
Dim lng_Ub                      As Long
    lng_lb = LBound(vBuff&())
    lng_Ub = UBound(vBuff&())
    If Not vBuff&(lng_Ub) > vBuff&(lng_lb) Then
        Dim t                           As Long
        t = lng_Ub
        lng_Ub = lng_lb
        lng_lb = t
    End If
    Do Until ExitsInArrayNR
        Select Case vValue
            Case vBuff&(lng_lb&)
                p& = lng_lb&
                ExitsInArrayNR = True
            Case vBuff&(lng_Ub&)
                p& = lng_Ub&
                ExitsInArrayNR = True
            Case Else
                p = (lng_lb& + lng_Ub&) / 2
                If p <> lng_lb& And p& <> lng_Ub& Then
                    If vBuff&(p&) < vValue& Then
                        lng_lb = p
                    ElseIf vBuff&(p&) > vValue& Then
                        lng_Ub = p
                    ElseIf vBuff&(p&) = vValue& Then
                        ExitsInArrayNR = True
                    End If
                Else
                    Exit Do
                End If
        End Select
    Loop
End Function

Resultado:


DoEvents! :P
50  Programación / Programación General / Duda simple expresiones regulares en: 7 Mayo 2011, 17:02 pm
Hola buenas, vengo aquí con un problemilla muy sencillo que tengo con RegExp.
Necesito validar nombres de usuario que sólo pueden contener : números, letras y "_" ; tener un mínimo de un carácter y un máximo de 15.
Para ello, pensé esto:
Código:
[\w_]{1,15}
El problema es que si tengo esto:
Código:
=Usu@rio^
La validación me da positiva, pues, encuentra caracteres alfanuméricos... :-(
Sólo quiero que me admita (\w y "_") nada más. ;)
¿Me echáis una mano?
Gracias :-*

DoEvents! :P
Páginas: 1 2 3 4 [5] 6 7 8 9 10 11 12 13 14 15 16 17
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines