Foro de elhacker.net

Programación => .NET (C#, VB.NET, ASP) => Mensaje iniciado por: luis456 en 16 Marzo 2015, 13:02 pm



Título: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: luis456 en 16 Marzo 2015, 13:02 pm
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
  1. 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}
  2.  
  3.  
  4.    Dim evensQuery = From num In numbers
  5.                         Where num Mod 2 = 0
  6.                         Select num
  7.  
  8.        Dim selectedValues As IEnumerable(Of Integer) = evensQuery.Take(4)
  9.        ListBox1.Items.AddRange(selectedValues.Cast(Of Object).ToArray)
  10.  
  11.        '----------------------------------------2
  12.        Dim ll = From num In numbers
  13.                Where num Mod 2 = 1
  14.                Select num
  15.  
  16.        Dim selected2Values As IEnumerable(Of Integer) = ll.Take(4)
  17.        ListBox2.Items.AddRange(selected2Values.Cast(Of Object).ToArray)
  18.  
  19.        '---------------------------------------------------------3
  20.        Dim ll1 = From num In numbers
  21.                Where num Mod 3 = 0
  22.                Select num
  23.  
  24.        Dim selected222Values As IEnumerable(Of Integer) = ll1.Take(4)
  25.        ListBox3.Items.AddRange(selected222Values.Cast(Of Object).ToArray)


Luis


Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: Eleкtro en 16 Marzo 2015, 15:33 pm
a 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


Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: luis456 en 16 Marzo 2015, 16:25 pm
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



 



Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: Eleкtro en 16 Marzo 2015, 17:37 pm
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

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
  1.    Dim evensQuery = From num In numbers
  2.                        Where num Mod 2 = 0
  3.                        Select num
  4.  
  5.        Dim ll = From num In numbers
  6.               Where num Mod 2 = 1
  7.               Select num
  8.  
  9.        Dim ll1 = From num In numbers
  10.               Where num Mod 3 = 0
  11.               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
  1. Public Class Form1
  2.  
  3.    Private Sub Test() Handles MyBase.Shown
  4.  
  5.        Dim values As IEnumerable(Of Integer) =
  6.            {
  7.                1, 2, 3, 4,
  8.                5, 6, 10, 11,
  9.                14, 15, 54, 57,
  10.                58, 60, 63, 64,
  11.                65, 67
  12.            }
  13.  
  14.        Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
  15.            SplitIntoParts(collection:=values, amount:=4,
  16.                           fillEmpty:=True)
  17.  
  18.        Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
  19.        Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
  20.        Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)
  21.  
  22.    End Sub
  23.  
  24.    ''' <remarks>
  25.    ''' *****************************************************************
  26.    ''' Snippet Title: Split Collection Into Parts
  27.    ''' Code's Author: Elektro
  28.    ''' Date Modified: 16-March-2015
  29.    ''' Usage Example:
  30.    ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  31.    ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = SplitColIntoParts(mainCol, amount:=4, fillEmpty:=True)
  32.    ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
  33.    '''                                 Debug.WriteLine(String.Join(", ", col))
  34.    '''                             End Sub)
  35.    ''' *****************************************************************
  36.    ''' </remarks>
  37.    ''' <summary>
  38.    ''' Splits an <see cref="IEnumerable(Of T)"/> into the specified amount of elements.
  39.    ''' </summary>
  40.    ''' <typeparam name="T"></typeparam>
  41.    ''' <param name="collection">The collection to split.</param>
  42.    ''' <param name="amount">The target elements amount.</param>
  43.    ''' <param name="fillEmpty">If set to <c>true</c>, generate empty elements to fill the last secuence's part amount.</param>
  44.    ''' <returns>IEnumerable(Of IEnumerable(Of T)).</returns>
  45.    Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
  46.                                                ByVal amount As Integer,
  47.                                                ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))
  48.  
  49.        Dim newCol As IEnumerable(Of List(Of T)) =
  50.            (From index As Integer
  51.            In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
  52.            Select collection.Skip(index * amount).Take(amount).ToList).ToList
  53.  
  54.        If fillEmpty Then
  55.  
  56.            Do Until newCol.Last.Count = amount
  57.                newCol.Last.Add(Nothing)
  58.            Loop
  59.  
  60.        End If
  61.  
  62.        Return newCol
  63.  
  64.    End Function
  65.  
  66. End Class

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

Código
  1.    Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
  2.                                                ByVal amount As Integer,
  3.                                                ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))
  4.  
  5.        Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
  6.               Select If(Not fillEmpty,
  7.                         collection.Skip(index * amount).Take(amount),
  8.                         If((collection.Count() - (index * amount)) >= amount,
  9.                            collection.Skip(index * amount).Take(amount),
  10.                            collection.Skip(index * amount).Take(amount).
  11.                                                            Concat(From i As Integer
  12.                                                                   In Enumerable.Range(0, amount - (collection.Count() - (index * amount)))
  13.                                                                   Select DirectCast(Nothing, T))))
  14.  
  15.    End Function

Saludos


Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: luis456 en 16 Marzo 2015, 18:46 pm
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


Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: luis456 en 17 Marzo 2015, 17:50 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
  1. Public Class Form1
  2.  
  3.    Private Sub Test() Handles MyBase.Shown
  4.  
  5.        Dim values As IEnumerable(Of Integer) =
  6.            {
  7.                1, 2, 3, 4,
  8.                5, 6, 10, 11,
  9.                14, 15, 54, 57,
  10.                58, 60, 63, 64,
  11.                65, 67
  12.            }
  13.  
  14.        Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
  15.            SplitIntoParts(collection:=values, amount:=4,
  16.                           fillEmpty:=True)
  17.  
  18.        Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
  19.        Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
  20.        Me.ListBox3.Items.AddRange(splits(2).Cast(Of Object).ToArray)
  21.  
  22.    End Sub
  23.  
  24.    ''' <remarks>
  25.    ''' *****************************************************************
  26.    ''' Snippet Title: Split Collection Into Parts
  27.    ''' Code's Author: Elektro
  28.    ''' Date Modified: 16-March-2015
  29.    ''' Usage Example:
  30.    ''' Dim mainCol As IEnumerable(Of Integer) = {1, 2, 3, 4, 5, 6, 7, 8, 9}
  31.    ''' Dim splittedCols As IEnumerable(Of IEnumerable(Of Integer)) = SplitColIntoParts(mainCol, amount:=4, fillEmpty:=True)
  32.    ''' splittedCols.ToList.ForEach(Sub(col As IEnumerable(Of Integer))
  33.    '''                                 Debug.WriteLine(String.Join(", ", col))
  34.    '''                             End Sub)
  35.    ''' *****************************************************************
  36.    ''' </remarks>
  37.    ''' <summary>
  38.    ''' Splits an <see cref="IEnumerable(Of T)"/> into the specified amount of elements.
  39.    ''' </summary>
  40.    ''' <typeparam name="T"></typeparam>
  41.    ''' <param name="collection">The collection to split.</param>
  42.    ''' <param name="amount">The target elements amount.</param>
  43.    ''' <param name="fillEmpty">If set to <c>true</c>, generate empty elements to fill the last secuence's part amount.</param>
  44.    ''' <returns>IEnumerable(Of IEnumerable(Of T)).</returns>
  45.    Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
  46.                                                ByVal amount As Integer,
  47.                                                ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))
  48.  
  49.        Dim newCol As IEnumerable(Of List(Of T)) =
  50.            (From index As Integer
  51.            In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
  52.            Select collection.Skip(index * amount).Take(amount).ToList).ToList
  53.  
  54.        If fillEmpty Then
  55.  
  56.            Do Until newCol.Last.Count = amount
  57.                newCol.Last.Add(Nothing)
  58.            Loop
  59.  
  60.        End If
  61.  
  62.        Return newCol
  63.  
  64.    End Function
  65.  
  66. End Class

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

Código
  1.    Public Shared Function SplitIntoParts(Of T)(ByVal collection As IEnumerable(Of T),
  2.                                                ByVal amount As Integer,
  3.                                                ByVal fillEmpty As Boolean) As IEnumerable(Of IEnumerable(Of T))
  4.  
  5.        Return From index As Integer In Enumerable.Range(0, CInt(Math.Ceiling(collection.Count() / amount)))
  6.               Select If(Not fillEmpty,
  7.                         collection.Skip(index * amount).Take(amount),
  8.                         If((collection.Count() - (index * amount)) >= amount,
  9.                            collection.Skip(index * amount).Take(amount),
  10.                            collection.Skip(index * amount).Take(amount).
  11.                                                            Concat(From i As Integer
  12.                                                                   In Enumerable.Range(0, amount - (collection.Count() - (index * amount)))
  13.                                                                   Select DirectCast(Nothing, T))))
  14.  
  15.    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
  1. Select(Function(Value As Integer)
  2.                      Return If(Value < MAX, Value, Rand.Next(1, MAX))
  3.                  End Function))


donde creo deberia ir ;(

Código
  1. Dim values As IEnumerable(Of Integer) =
  2.            {
  3.                1, 2, 3, 4,
  4.                5, 6, 10, 11,
  5.                14, 15, 54, 57,
  6.                58, 60, 61, 64,
  7.                65, 67, 71, 75
  8.            }
  9.        Dim Re3 As New Random
  10.        Dim splits As IEnumerable(Of IEnumerable(Of Integer)) =
  11.            SplitIntoParts(collection:=values, amount:=4,
  12.                           fillEmpty:=True)
  13.  
  14.  
  15.        Me.ListBox1.Items.AddRange(splits(0).Cast(Of Object).ToArray)
  16.        Me.ListBox2.Items.AddRange(splits(1).Cast(Of Object).ToArray)
  17.        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



Título: Re: tomar valores de una cadena numerica y agrupar en variables independientes
Publicado por: luis456 en 18 Marzo 2015, 07:53 am
 ;-) ;-) ;-) ;-) ;-) ;-) ;-) y yo solito era muy facil jejejje

Código
  1. Dim Re3 As New Random
  2.        Dim ReAsult2255e As IEnumerable(Of Integer) =
  3.           (splits(0).Concat(splits(2).
  4.           Distinct.
  5.           Select(Function(Value As Integer)
  6.                      Return If(Value < MAX, Value, Rand.Next(1, MAX))
  7.                  End Function)))
  8.  
  9.        Dim seAlecctedValues231 As IEnumerable(Of Integer) = ReAsult2255e
  10.        Dim liste3 As List(Of Integer) = ReAsult2255e.Take(11).ToList
  11.  
  12.        liste3.Sort()
  13.        ListBox6.Items.AddRange(liste3.Cast(Of Object).ToArray)