LinkedList C#
Publicado: 04 Feb 2016, 00:05
por sanko
Bueno, la semana pasada tuve mi primer laboratorio de TPP y se nos pidieron 2 tareas facilitas para ir familiarizandonos con la sintáxis de C#, que es el lenguaje que empezaremos a usar en dicha asignatura.
Foto del PDF1: Node.cs
Collection.cs <<Interface>>
List.cs <<Interface>>
LinkedList.cs
Pruebas Unitarias:
Ejemplo de uso: CLI
PDF Tarea 2:
Geometria.cs
Programa de consola: ejemplo de uso
A alguien le servirá, he tenido que esperar pa subirlo porque ya me he enterao que algún compañero se pasa solo por indetectables para saber si he subido la tarea xd, jódase.
Foto del PDF1: Node.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Colletions
{
/// <summary>
/// Node class
/// </summary>
public class Node
{
public Object value { get; protected internal set; }
public Node next { get; protected internal set; }
public Node(Object value, Node next)
{
this.value = value;
this.next = next;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Colletions
{
/// <summary>
/// Collection Interface
/// </summary>
public interface Collection
{
/// <summary>
/// Add method: add an object by value
/// </summary>
/// <param name="value">received object to add inside the collection</param>
void add(Object value);
/// <summary>
/// Remove method: remove an object by value
/// </summary>
/// <param name="value">received object to remove an element of the collection</param>
/// <returns>The object that was removed</returns>
Object remove(Object value);
/// <summary>
/// Size method: indicates you the number of elements that have the collection
/// </summary>
/// <returns>An integer</returns>
int size();
/// <summary>
/// isEmpty method: indicates you if the collection is empty or not (0 elements)
/// </summary>
/// <returns>A boolean, true if is empty or false if not</returns>
Boolean isEmpty();
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Colletions
{
/// <summary>
/// List Interface - Implements collection interface
/// </summary>
public interface List : Collection
{
/// <summary>
/// Add method: you can add an element by index
/// </summary>
/// <param name="index">Integer that indicates you the position where you want to add the element</param>
/// <param name="value">An object you want to add inside the list</param>
void add(int index, Object value);
/// <summary>
/// Remove by Index method: allows you to remove an element by his position
/// </summary>
/// <param name="index">Integer representing the position of the element</param>
/// <returns>The object you removed</returns>
Object removeByIndex(int index);
/// <summary>
/// indexOf Method: Allos you to know in wich position is an element
/// </summary>
/// <param name="value">The object you want to know his position</param>
/// <returns>An integer representing the position of the element</returns>
int indexOf(Object value);
/// <summary>
/// Get method: Allows you to get an element by his position
/// </summary>
/// <param name="index">The position o the element you want to get</param>
/// <returns>An object/element you want to get</returns>
Object get(int index);
/// <summary>
/// Set method: Allows you to set the value of an element in an specific position
/// </summary>
/// <param name="index">The position of the element</param>
/// <param name="value">The element/object you want to set</param>
void set(int index, Object value);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Author: Esteban Montes Morales
/// Subject: TPP at uniovi
/// </summary>
namespace Colletions
{
/// <summary>
/// LinkedList Class
/// </summary>
public class LinkedList : List {
public Node head { get; private set; }
public int counter { get; private set; }
/// <summary>
/// Method for get a node by an index
/// </summary>
/// <param name="index">The position of the node you want to get</param>
/// <returns>The wanted Node</returns>
private Node getNode(int index){
Node node = head;
int pos = 0;
while(pos<index){
node = node.next;
pos++;
}
return node;
}
public void add(object value){
if (isEmpty())
head = new Node(value, null);
else{
Node last = getNode(size()-1);
last.next = new Node(value, null);
}
counter++;
}
public void add(int index, object value){
if (index >= 0 && index < size()){
if (isEmpty())
head = new Node(value, null);
else if (index == 0){
head = new Node(value, head.next);
}
else{
Node previous = getNode(index - 1);
previous.next = new Node(value, previous.next);
}
counter++;
}
}
public object get(int index){
return getNode(index).value;
}
public void set(int index, object value){
getNode(index).value = value;
}
/// <summary>
/// Method that extract all indexes(position) of a value and return all as a int[] array
/// </summary>
/// <param name="value"></param>
/// <returns>An array of integers</returns>
public int[] allIndexesOf(object value){
return (from num in Enumerable.Range(0, counter).ToArray() where getNode(num).value.Equals(value) select num).ToArray();
}
public int indexOf(object value){
int indexOf = -1;
for(int i=0; i< counter; i++){
if(getNode(i).value.Equals(value)){
indexOf = i;
return indexOf;
}
}
return indexOf;
}
public bool isEmpty(){
return (counter==0);
}
public object remove(object value){
Node currentNode = null;
if (size() != 0)
{
int index = indexOf(value);
if (index != -1) {
currentNode = getNode(index);
if (index != 0){
Node previous = getNode(index - 1);
previous.next = currentNode.next;
}
else {
head = head.next;
}
counter--;
}
}
return currentNode.value;
}
/// <summary>
/// Remove all elements with the same value
/// </summary>
/// <param name="value">An array of objects(removed elements)</param>
/// <returns></returns>
public object[] removeAllValues(object value) {
int[] indexes = allIndexesOf(value);
object[] result = new object[indexes.Length];
for (int i=0; i<indexes.Length; i++) {
result[i] = removeByIndex(indexes[i]);
indexes = (from j in indexes.Select(x => x - 1) select j).ToArray();
}
return result;
}
public object removeByIndex(int index){
//empty or out of limits
if(isEmpty() || index<0 || index>=size()){
return null;
}
Object value;
if (index == 0){
value = head.value;
head = head.next;
}
else{
Node previous = getNode(index-1);
value = previous.next.value;
previous.next = previous.next.next;
}
counter--;
return value;
}
public int size(){
return counter;
}
public override String ToString(){
StringBuilder sb = new StringBuilder("[");
Node node = head;
for (int i = 0; i < size(); i++){
if(i==size()-1)
sb.Append(node.value.ToString());
else
sb.Append(node.value.ToString()).Append(", ");
node = node.next;
}
sb.Append("]");
return sb.ToString();
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
/// <summary>
/// Author: Esteban Montes Morales
/// Subject: TPP at uniovi
/// </summary>
namespace ListTest
{
//*PD: NOT EXHAUSTIVE TESTS
[TestClass]
public class UnitTest1
{
Colletions.LinkedList list = new Colletions.LinkedList();
[TestMethod]
public void TestAdd(){
list = new Colletions.LinkedList();
//Positive tests
//Adding objects:
//Adding Integers or ints
list.add(1);
Assert.AreEqual(1, list.size());
//Adding Strings and Chars
list.add("a");
Assert.AreEqual(2, list.size());
}
[TestMethod]
public void TestGet(){
list = new Colletions.LinkedList();
for(int i=0; i<50; i++){
list.add(i);
Assert.AreEqual(i+1, list.size());
}
list.add(2, 999);
Assert.AreEqual(999, list.get(2));
Assert.AreEqual(2, list.get(3));
Assert.AreEqual(1, list.get(1));
list = new Colletions.LinkedList();
for (int i = 0; i < 50; i++)
{
list.add(i);
Assert.AreEqual(i + 1, list.size());
}
list.add(0,999);
Assert.AreEqual(999, list.get(0));
//System.Console.WriteLine(list.size());
list.add(list.size()-1, 888);
Assert.AreEqual(49, list.get(list.size() - 3));
Assert.AreEqual(888, list.get(list.size()-2));
}
[TestMethod]
public void TestAddByPosition(){
list = new Colletions.LinkedList();
for (int i = 0; i < 50; i++)
{
list.add(i);
Assert.AreEqual(i + 1, list.size());
}
//Positive tests
//Implemented inside TestGet() for testing both methods
//Negative tests
//index>=size
list.add(list.size(), 999);
list.add(list.size()+1, 999);
Assert.AreEqual(50, list.size());
//index<0
list.add(-6, 999);
Assert.AreEqual(50, list.size());
}
[TestMethod]
public void TestRemove() {
list = new Colletions.LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(1);
list.add(3);
// 1, 2, 3, 1, 3, remove(3) -> 1,2,1,3
Assert.AreEqual(3, list.remove(3));
Assert.AreEqual(4, list.size());
Assert.AreEqual(1, list.get(0));
Assert.AreEqual(2, list.get(1));
Assert.AreEqual(1, list.get(2));
Assert.AreEqual(3, list.get(3));
}
[TestMethod]
public void testRemoveByIndex() {
list = new Colletions.LinkedList();
Colletions.LinkedList list2 = new Colletions.LinkedList();
Colletions.LinkedList list3 = new Colletions.LinkedList();
for (int i = 0; i < 50; i++)
{
list.add(i);
list2.add(i);
list3.add(i);
}
//remove first element
list.removeByIndex(0);
Assert.AreEqual(1, list.get(0));
Assert.AreEqual(49, list.size());
//remove last element
list.removeByIndex(list.size()-1);
Assert.AreEqual(48, list.get(list.size() - 1));
Assert.AreEqual(48, list.size());
//remove [firstElement, lastElement]
Assert.AreEqual(0, list2.removeByIndex(0));
Assert.AreEqual(25+1, list2.removeByIndex(25));
Assert.AreEqual(32+2, list2.removeByIndex(32));
//Assert.AreEqual(49, list2.removeByIndex(list2.size()-1));
//remove all
for (int i = 0; i < 50; i++)
{
list3.removeByIndex(0);
}
Assert.AreEqual(0, list3.size());
//Negative tests
//Index >= size
//Index < 0
}
[TestMethod]
public void testSize()
{
list = new Colletions.LinkedList();
//list.add(1);
//Assert.AreEqual(1, list.size());
//adding elems
for (int i=1; i<51; i++) {
list.add(i);
Assert.AreEqual(i, list.size());
}
//removing elems
for (int i = 1; i < 51; i++){
list.remove(i);
Assert.AreEqual(50-i, list.size());
}
}
[TestMethod]
public void testIndexOf(){
list = new Colletions.LinkedList();
for (int i=0; i<50; i++) {
list.add(i);
Assert.AreEqual(i, list.indexOf(i));
}
}
[TestMethod]
public void testAllIndexesOf() {
list = new Colletions.LinkedList();
for (int i=0; i<10; i++) {
list.add(1);
}
int[] expected = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Assert.AreEqual(expected.Length, list.size());
CollectionAssert.AreEqual(expected, list.allIndexesOf(1));
}
[TestMethod]
public void testRemoveAllValues() {
list = new Colletions.LinkedList();
for (int i = 0; i < 10; i++)
{
list.add(1);
}
list.add(2);
list.add(3);
int auxSize = list.size();
object[] expected = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
object[] result = list.removeAllValues(1);
CollectionAssert.AreEqual(expected, result);
Assert.AreEqual(expected.Length, result.Length);
Assert.AreEqual(auxSize-result.Length, list.size());
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UsoList
{
class Program
{
static void Main(string[] args)
{
//Usage sample
Colletions.LinkedList list = new Colletions.LinkedList();
//ADDING OPERATIONS
list.add(1);
list.add(2);
list.add(3);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(6);
list.add(6);
list.add(6);
list.add(1, 1); // adding by index
Console.WriteLine(list.ToString());
//REMOVE
list.remove(1);
list.remove(2);
list.removeByIndex(4); //removing by index
list.removeAllValues(6); //removing all '6' in the linkedlist
Console.WriteLine(list.ToString());
//INDEXOF
Console.WriteLine("El 3 se encuentra en la posición {0}", list.indexOf(3));
int[] indexes = list.allIndexesOf(3);
String positions = "[ ";
for (int i=0; i<indexes.Length; i++) {
if (i != indexes.Length - 1)
positions += indexes[i] + ", ";
else
positions += indexes[i] + " ]";
}
Console.WriteLine("Estas son todas las posiciones en las que hay un 3: {0}", positions);
//SIZE
Console.WriteLine("El tamaño de la lista actualmente es: {0}", list.size());
//GET/SET
Console.WriteLine("El primer elemento de la lista es el: {0}", list.get(0));
list.set(0, 10);
Console.WriteLine("Ahora el primer elemento a cambiado (tras usar el setter)");
Console.WriteLine("El primer elemento de la lista es el: {0}", list.get(0));
/// ...
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practica1
{
//*NOTA: No se han implementado getters ni setters, esta tarea la he desarrollado durante la primera práctica de TPP
// donde básicamente estabamos haciendo una toma de contacto con el lenguaje
/// <summary>
/// Clase para representar un punto en un espacio 2D
/// </summary>
public class Punto2d {
public double x;
public double y;
public Color c;
/// <summary>
/// Constructor con parametros
/// </summary>
/// <param name="laX">Punto x en el espacio euclideo</param>
/// <param name="laY">Punto y en el espacio euclideo</param>
/// <param name="elColor">Color, tipo enumerado donde definiremos el color</param>
public Punto2d(double laX, double laY, Color elColor) {
this.x = laX;
this.y = laY;
this.c = elColor;
}
/// <summary>
/// Distancia entre 2 puntos
/// </summary>
/// <param name="a">Punto al que llegar</param>
/// <returns></returns>
public double distancia(Punto2d a) {
return Math.Sqrt((this.x - a.x) * (this.x - a.x) + (this.y - a.y) * (this.y - a.y));
}
/// <summary>
/// Método toString que mostrará la información genérica de la Clase
/// </summary>
/// <returns></returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder("x=");
sb.Append(this.x);
sb.Append(", y=");
sb.Append(this.y);
sb.Append(", Color=");
sb.Append(this.c);
return sb.ToString();
}
}
public class Recta {
/// <summary>
/// Atributo para definir m en la ecuacion de la recta
/// </summary>
public double m;
/// <summary>
/// Atributo para definir n en la ecuación de la recta
/// </summary>
public double n;
/// <summary>
/// Constructor con parametros para la Recta
/// </summary>
/// <param name="m">punto origen, Valor doble</param>
/// <param name="n">punto destino, Valor doble</param>
public Recta(double m, double n) {
this.m = m;
this.n = n;
}
/// <summary>
/// Método para calcular el punto en el que se produce la intersección de una recta
/// </summary>
/// <param name="b">Recta a intersectar</param>
/// <returns>Un punto</returns>
public Punto2d interseccionRecta(Recta b) {
double corteY = ((this.n/this.m) - (b.n/b.m))/((1/this.m)-(1/b.m));
double corteX = (corteY - b.n)/b.m;
return new Punto2d(corteX, corteY, Color.Negro);
}
/// <summary>
/// Método para calcular la perpendicular de un punto, devuelve una recta(perpendicular)
/// </summary>
/// <param name="punto">Punto desde el que se obtiene la recta perpendicular</param>
/// <returns>Una recta</returns>
public Recta perpendicular(Punto2d punto) {
double nuevaM = (-1 / this.m);
double nuevaN = ((punto.y + (1 / this.m) * punto.x));
return new Recta(nuevaM, nuevaN);
}
/// <summary>
/// Método para calcular la distancia entre una recta y un punto
/// </summary>
/// <param name="a">a es el Punto desde el que se calculara la distancia hacia la recta, para ello hacemos uso
/// de los anteriores métodos
/// </param>
/// <returns>Retorna un valor doble, que será la distancia entre dicha recta y punto</returns>
public double distanciaEntreRectaYPunto(Punto2d a){
Recta rectaAux = perpendicular(a);
Punto2d interseccion = interseccionRecta(rectaAux);
return a.distancia(interseccion);
}
/// <summary>
/// Método redefinido para mostrar la información de la clase como nosotros gustemos o requiramos
/// </summary>
/// <returns>Devuelve un String</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("y=" + this.m + "x" + "+" + this.n);
return sb.ToString();
}
/// <summary>
/// Destructor que liberara la memoria, en este caso no es muy util puesto que no tenemos recursos suficientes para usarlo
/// Igualmente, es un ejemplo de uso
/// </summary>
~Recta()
{
System.Diagnostics.Trace.WriteLine("Se ha llamado al destructor de Recta");
}
}
/// <summary>
/// Enumerado donde definimos los colores disponibles para nuestras formas geométricas
/// </summary>
public enum Color {
/// <summary>
/// Color transparente
/// </summary>
Transparente,
/// <summary>
/// Color negro
/// </summary>
Negro,
/// <summary>
/// Color rojo
/// </summary>
Rojo
};
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Practica1
{
class Program
{
static void Main(string[] args)
{
//DISTANCIA ENTRE PUNTOS
Punto2d a = new Punto2d(10, 20, Color.Negro);
Punto2d b = new Punto2d(20, 10, Color.Rojo);
Console.WriteLine("Punto A: {0} || Punto B: {1}", a.ToString(), b.ToString());
Console.WriteLine("La distancia entre el punto A y el punto B es => {0}", a.distancia(b));
//INTERSECCIÓN RECTA
Recta y0 = new Recta(50, 60);
Recta y1 = new Recta(60, 50);
Console.WriteLine("Intersección de las rectas se produce en el punto: {0}", y0.interseccionRecta(y1));
//PERPENDICULAR DE UN PUNTO
Console.WriteLine("La perpendicular del punto A es: {0}", y0.perpendicular(a));
//DISTANCIA ENTRE RECTA Y PUNTO
Console.WriteLine("Distancia entre la perpendicular y el punto donde intersecta: {0}", y0.distanciaEntreRectaYPunto(a));
}
}
}