tomar valores de una cadena numerica y agrupar en variables independientes

Iniciado por luis456, 16 Marzo 2015, 13:02 PM

0 Miembros y 1 Visitante están viendo este tema.

luis456

Estaba trabajando este código pero después de escribir la ostia a medida que alargo los números estos se quedan cortos ;(

yo lo que busco es pasar los números de la cadena por orden de menor a mayor en grupos de cuatro en cada variable pero necesito saber los nombres de las variable

ejemplo
variable a=(valor de 1 2 3 4)
variable b=(valor de 5 6 10 11 )

Código (vbnet) [Seleccionar]
Dim numbers() As Integer = {1, 2, 3, 4, 5, 6, 10, 11, 14, 15,  54, 57, 58, 60, 63, 64, 65, 67, 68, 69, 70, 71, 75, 76, 77, 79, 80}


   Dim evensQuery = From num In numbers
                        Where num Mod 2 = 0
                        Select num

       Dim selectedValues As IEnumerable(Of Integer) = evensQuery.Take(4)
       ListBox1.Items.AddRange(selectedValues.Cast(Of Object).ToArray)

       '----------------------------------------2
       Dim ll = From num In numbers
               Where num Mod 2 = 1
               Select num

       Dim selected2Values As IEnumerable(Of Integer) = ll.Take(4)
       ListBox2.Items.AddRange(selected2Values.Cast(Of Object).ToArray)

       '---------------------------------------------------------3
       Dim ll1 = From num In numbers
               Where num Mod 3 = 0
               Select num

       Dim selected222Values As IEnumerable(Of Integer) = ll1.Take(4)
       ListBox3.Items.AddRange(selected222Values.Cast(Of Object).ToArray)



Luis
Que tu sabiduria no sea motivo de Humillacion para los demas

Eleкtro

Cita de: luis456 en 16 Marzo 2015, 13:02 PMa medida que alargo los números estos se quedan cortos ;(

¿Qué?.

Compila el código que has mostrado, mira el resultado que da (2,4,6,10 | 1,3,5,11 | 3,6,15,54), y explica que resultado sería el que esperas obtener.

Saludos








luis456

Funciona bien pero a medida que los números del arreglo se hace mas largo estos resultados se vuelven inestables y ya no me sigue la secuencia .

simplemente quiero asignar los primero 4 números del arreglo a Variable  (A)  desde el quinto numero a variable (B)  y asi sucesivamente realmente son posiciones  en fox se hacia con el ( largo ) pero aca a pesar de que tengo la mañana viendo y re viendo no entiendo la sintexis

Arreglo NÚMEROS = (1, 2, 3, 4, 5, 6, 10, 11, 14, 15,  54, 57, 58, 60, 63, 64, 65, 67,)

Esta seria la salida

A=01, 02, 03, 04,
B=05, 06, 10, 11,
C=14, 15,  54, 57
D=58, 60, 63, 64
E= 65, 67, 00  00 <---aca me las arreglo con un pedazo de código tuyo :) para completar


Luis





Que tu sabiduria no sea motivo de Humillacion para los demas

Eleкtro

Cita de: luis456 en 16 Marzo 2015, 16:25 PMArreglo NÚMEROS = (1, 2, 3, 4, 5, 6, 10, 11, 14, 15,  54, 57, 58, 60, 63, 64, 65, 67,)

Esta seria la salida

A=01, 02, 03, 04,
B=05, 06, 10, 11,
C=14, 15,  54, 57
D=58, 60, 63, 64
E= 65, 67, 00  00 <---aca me las arreglo con un pedazo de código tuyo :) para completar

Eso es una simple partición, que no concuerda en absoluto con las colecciones que estás generando en el primer código que mostraste, donde utilizas el operador Mod para filtrar la secuencia y, claro está, da un resultado muy diferente al que has hecho referencia ahora:

Citar
Código (vbnet) [Seleccionar]
   Dim evensQuery = From num In numbers
                       Where num Mod 2 = 0
                       Select num

       Dim ll = From num In numbers
              Where num Mod 2 = 1
              Select num

       Dim ll1 = From num In numbers
              Where num Mod 3 = 0
              Select num

¿Entonces?.




En el primer caso, es decir, partir la colección en colecciones de 4 partes (cosa que ya te mostré cómo hacerlo) y rellenar con "ceros" los elementos restantes de la última "parte", es tan sencillo cómo esto:

Código (vbnet) [Seleccionar]
Public Class Form1

   Private Sub Test() Handles MyBase.Shown

       Dim values As IEnumerable(Of Integer) =
           {
               1, 2, 3, 4,
               5, 6, 10, 11,
               14, 15, 54, 57,
               58, 60, 63, 64,
               65, 67
           }

       Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
           SplitIntoParts(collection:=values, amount:=4,
                          fillEmpty:=True)

       Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
       Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
       Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)

   End Sub

   ''' <remarks>
   ''' *****************************************************************
   ''' Snippet Title: Split Collection Into Parts
   ''' Code's Author: Elektro
   ''' Date Modified: 16-March-2015
   ''' Usage Example:
   ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = SplitColIntoParts(mainCol, amount:=4, fillEmpty:=True)
   ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                 Debug.WriteLine(String.Join(", ", col))
   '''                             End Sub)
   ''' *****************************************************************
   ''' </remarks>
   ''' <summary>
   ''' Splits an <see cref="IEnumerable(Of T)"/> into the specified amount of elements.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="collection">The collection to split.</param>
   ''' <param name="amount">The target elements amount.</param>
   ''' <param name="fillEmpty">If set to <c>true</c>, generate empty elements to fill the last secuence's part amount.</param>
   ''' <returns>IEnumerable(Of IEnumerable(Of T)).</returns>
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Dim newCol As IEnumerable(Of List(Of T)) =
           (From index As Integer
           In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
           Select collection.Skip(index * amount).Take(amount).ToList).ToList

       If fillEmpty Then

           Do Until newCol.Last.Count = amount
               newCol.Last.Add(Nothing)
           Loop

       End If

       Return newCol

   End Function

End Class


EDITO:
Una actualización de la función:

Código (vbnet) [Seleccionar]
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
              Select If(Not fillEmpty,
                        collection.Skip(index * amount).Take(amount),
                        If((collection.Count() - (index * amount)) >= amount,
                           collection.Skip(index * amount).Take(amount),
                           collection.Skip(index * amount).Take(amount).
                                                           Concat(From i As Integer
                                                                  In Enumerable.Range(0, amount - (collection.Count() - (index * amount)))
                                                                  Select DirectCast(Nothing, T))))

   End Function


Saludos








luis456

Diossssssssssss elektro

no te suena algo de esto ?

a=1
b=2
a+b= 3

Jejejjje es Broma  lo probare y te cuento ya que seguro que alguna pega tendre :(

luis
Que tu sabiduria no sea motivo de Humillacion para los demas

luis456

Cita de: Eleкtro en 16 Marzo 2015, 17:37 PM
Eso es una simple partición, que no concuerda en absoluto con las colecciones que estás generando en el primer código que mostraste, donde utilizas el operador Mod para filtrar la secuencia y, claro está, da un resultado muy diferente al que has hecho referencia ahora:

¿Entonces?.




En el primer caso, es decir, partir la colección en colecciones de 4 partes (cosa que ya te mostré cómo hacerlo) y rellenar con "ceros" los elementos restantes de la última "parte", es tan sencillo cómo esto:

Código (vbnet) [Seleccionar]
Public Class Form1

   Private Sub Test() Handles MyBase.Shown

       Dim values As IEnumerable(Of Integer) =
           {
               1, 2, 3, 4,
               5, 6, 10, 11,
               14, 15, 54, 57,
               58, 60, 63, 64,
               65, 67
           }

       Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
           SplitIntoParts(collection:=values, amount:=4,
                          fillEmpty:=True)

       Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
       Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
       Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)

   End Sub

   ''' <remarks>
   ''' *****************************************************************
   ''' Snippet Title: Split Collection Into Parts
   ''' Code's Author: Elektro
   ''' Date Modified: 16-March-2015
   ''' Usage Example:
   ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
   ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = SplitColIntoParts(mainCol, amount:=4, fillEmpty:=True)
   ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
   '''                                 Debug.WriteLine(String.Join(", ", col))
   '''                             End Sub)
   ''' *****************************************************************
   ''' </remarks>
   ''' <summary>
   ''' Splits an <see cref="IEnumerable(Of T)"/> into the specified amount of elements.
   ''' </summary>
   ''' <typeparam name="T"></typeparam>
   ''' <param name="collection">The collection to split.</param>
   ''' <param name="amount">The target elements amount.</param>
   ''' <param name="fillEmpty">If set to <c>true</c>, generate empty elements to fill the last secuence's part amount.</param>
   ''' <returns>IEnumerable(Of IEnumerable(Of T)).</returns>
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Dim newCol As IEnumerable(Of List(Of T)) =
           (From index As Integer
           In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
           Select collection.Skip(index * amount).Take(amount).ToList).ToList

       If fillEmpty Then

           Do Until newCol.Last.Count = amount
               newCol.Last.Add(Nothing)
           Loop

       End If

       Return newCol

   End Function

End Class


EDITO:
Una actualización de la función:

Código (vbnet) [Seleccionar]
   Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
                                               ByVal amount As Integer,
                                               ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))

       Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
              Select If(Not fillEmpty,
                        collection.Skip(index * amount).Take(amount),
                        If((collection.Count() - (index * amount)) >= amount,
                           collection.Skip(index * amount).Take(amount),
                           collection.Skip(index * amount).Take(amount).
                                                           Concat(From i As Integer
                                                                  In Enumerable.Range(0, amount - (collection.Count() - (index * amount)))
                                                                  Select DirectCast(Nothing, T))))

   End Function


Saludos



Funciona bien ya te habías preocupado no ? era justo lo que queria hacer ya que me deja mucho campo para mi investigacion :)  ahora estoy tratando de mejorarlo con un codigo que me diste te muestro y como te lo paso se que no funciona pero es para la idea de relleñar las variables cuando no hay mas numeros  con los numeros aleatorios dentro del rango


tu funcion

Código (vbnet) [Seleccionar]
Select(Function(Value As Integer)
                      Return If(Value < MAX, Value, Rand.Next(1, MAX))
                  End Function))



donde creo deberia ir ;(

Código (vbnet) [Seleccionar]
Dim values As IEnumerable(Of Integer) =
            {
                1, 2, 3, 4,
                5, 6, 10, 11,
                14, 15, 54, 57,
                58, 60, 61, 64,
                65, 67, 71, 75
            }
        Dim Re3 As New Random
        Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
            SplitIntoParts(collection:=values, amount:=4,
                           fillEmpty:=True)


        Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
        Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
        Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)   



ya he tratado yo jejeje pero a la final el ordenador me dijo Veta a tomar por el c,, Viejo inutil


luis

Que tu sabiduria no sea motivo de Humillacion para los demas

luis456

 ;-) ;-) ;-) ;-) ;-) ;-) ;-) y yo solito era muy facil jejejje

Código (vbnet) [Seleccionar]
Dim Re3 As New Random
        Dim ReAsult2255e As IEnumerable(Of Integer) =
           (splits(0).Concat(splits(2).
           Distinct.
           Select(Function(Value As Integer)
                      Return If(Value < MAX, Value, Rand.Next(1, MAX))
                  End Function)))

        Dim seAlecctedValues231 As IEnumerable(Of Integer) = ReAsult2255e
        Dim liste3 As List(Of Integer) = ReAsult2255e.Take(11).ToList

        liste3.Sort()
        ListBox6.Items.AddRange(liste3.Cast(Of Object).ToArray)



Que tu sabiduria no sea motivo de Humillacion para los demas