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

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Necesito ayuda con un program en c#
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Necesito ayuda con un program en c#  (Leído 1,884 veces)
Emily

Desconectado Desconectado

Mensajes: 18


Ver Perfil
Necesito ayuda con un program en c#
« en: 19 Marzo 2017, 10:21 am »

hola me preguntaba si alguien podría ayudarme con un programa en c#
necesito ingresar 10 números en un vector y los números que se repiten los tengo que poner con 0
Tiene que imprimir esto:
Suponga los valores de entrada del arreglo:

10 4 9 11 4 7 10 30 11 10

El resultado sería:

10 4 9 11 0 7 0 30 0 0


En línea

Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.788



Ver Perfil
Re: Necesito ayuda con un program en c#
« Respuesta #1 en: 19 Marzo 2017, 11:55 am »

Hola. ¿Cual es la razón que te ha llevado a publicar una pregunta sobre C#, en el foro de Visual Basic 6? :-\

Bueno, una forma de hacer lo que pides en caso de que quieras preservar los elementos del array original sin modificar, sería desarrollar una función genérica para iterarlo de la siguiente manera:

Código
  1. /// ----------------------------------------------------------------------------------------------------
  2. /// <summary>
  3. /// Replaces the duplicated items in the source collection using the specified value.
  4. /// </summary>
  5. /// ----------------------------------------------------------------------------------------------------
  6. /// <typeparam name="T">
  7. /// The type of the items in te collection.
  8. /// </typeparam>
  9. ///
  10. /// <param name="collection">
  11. /// The source collection.
  12. /// </param>
  13. ///
  14. /// <param name="value">
  15. /// The value that will be used to replace duplicated items.
  16. /// </param>
  17. /// ----------------------------------------------------------------------------------------------------
  18. /// <returns>
  19. /// The resulting <see cref="IEnumerable&lt;T&gt;"/>.
  20. /// </returns>
  21. /// ----------------------------------------------------------------------------------------------------
  22. public static IEnumerable<T> ReplaceDuplicates<T>(T[] collection, T value) {
  23.  
  24.    HashSet<T> hset = new HashSet<T>();
  25.  
  26.    foreach(T item in collection) {
  27.        if (hset.Add(item)) {
  28.            yield return item;
  29.        } else {
  30.            yield return value;
  31.        }
  32.    }
  33.  
  34. }

Modo de empleo:
Código
  1. int[] arr = { 10, 4, 9, 11, 4, 7, 10, 30, 11, 10 };
  2. int[] newArr = ReplaceDuplicates<int>(arr, 0).ToArray();
  3.  
  4. Console.WriteLine(string.Join(", ", newArr));

Resultado de ejecución:
Cita de: Visual Studio's Debug Window Output
10, 4, 9, 11, 0, 7, 0, 30, 0, 0

Hay varias formas de hacerlo. También puedes utilizar un for para reemplazar los elementos del array original, o recurrir al elegante pero no muy eficiente LINQ.

EDITO: Por ejemplo:
Código
  1. int[] arr = { 10, 4, 9, 11, 4, 7, 10, 30, 11, 10 };
  2. int[] newArr = arr.Select((a, b) => Array.IndexOf(arr, a) == b ? a : 0).ToArray();
  3.  
  4. Console.WriteLine(string.Join(", ", newArr));

¡Saludos!


« Última modificación: 19 Marzo 2017, 14:15 pm por Eleкtro » En línea

okik


Desconectado Desconectado

Mensajes: 462


Ver Perfil
Re: Necesito ayuda con un program en c#
« Respuesta #2 en: 19 Marzo 2017, 12:36 pm »

Código
  1. using System;
  2. using System.Linq;
  3. ...
  4.  



Citar
int[] MiArray = {10,4,9,11,4,7,10,30,11,10};
        
for (int Index = 0; Index <= MiArray.Length - 1; Index++) {
    //Cuenta el número  que se repite un elemento del array
    var CountItems = (from ItemRep in MiArray where (ItemRep == MiArray[Index]) select ItemRep).ToList().Count;
    if (CountItems > 1)
    {
        MiArray[MiArray.ToList().LastIndexOf(MiArray[Index])] = 0;
    }
}

Console.WriteLine(string.Join(", ", MiArray));
Console.ReadLine();



He rectificado el código anterior, ya me pareció extraño que resultara. En el caso de "10, 4, 4, 4, 4, 4, 4, ", no hubiera devuelto "10,4,0,0,0,0,0".

Código
  1.            int[] MiArray = { 10, 4, 9, 11, 4, 7, 10, 30, 11, 10 };
  2.  
  3.  
  4.            foreach (var Item in MiArray)
  5.            {
  6.                for (int Index = MiArray.ToList().IndexOf(Item) + 1; Index <= MiArray.Length - 1; Index++)
  7.                {
  8.                    if (MiArray[Index] == Item) { MiArray[Index] = 0; };
  9.                }
  10.            }
  11.            Console.WriteLine(String.Join(",", MiArray));
  12.            Console.ReadLine();

Código:
10, 4, 9, 11, 0, 7, 0, 30, 0, 0


Así también funcionaría:
Código
  1.  int[] MiArray = { 10, 4, 9, 11, 4, 7, 10, 4, 4, 4 };
  2.  
  3.  
  4.            for (int frtIndex = 0; frtIndex <= MiArray.Length - 1; frtIndex++)
  5.            {
  6.                for (int scdIndex = frtIndex + 1; scdIndex <= MiArray.Length - 1; scdIndex++)
  7.                {
  8.                    if (MiArray[scdIndex] == MiArray[frtIndex]) { MiArray[scdIndex] = 0; };
  9.                }
  10.            }
  11.            Console.WriteLine(String.Join(",", MiArray));
  12.            Console.ReadLine();
  13.  
  14.  

Código:
10, 4, 9, 11, 0, 7, 0, 0, 0, 0
« Última modificación: 19 Marzo 2017, 14:07 pm por okik » En línea

Emily

Desconectado Desconectado

Mensajes: 18


Ver Perfil
Re: Necesito ayuda con un program en c#
« Respuesta #3 en: 19 Marzo 2017, 14:37 pm »

Muchisimas Gracias :D
Me a ayudado mucho
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines