sábado, 15 de junio de 2013
Proyecto Arbol Binario
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
namespace ArbolBinario
{
class Program
{
static void Main(string[] args)
{
OleDbConnection MyConnection = new OleDbConnection(ConfigurationManager.AppSettings["AccessConnection"].ToString());
string x = string.Empty;
string value= string.Empty;
string[] List = new string[6];
do
{
Console.Write("\n\nMenú \n 1)Mostrar árbol binario \n 2)Creación de nodos \n 3)Eliminación de nodo \n 4)Mostrar Recorridos \n 0)Salir \n\n");
x = Console.ReadLine();
switch (x)
{
case "1":
ShowBinaryTree(MyConnection);
break;
case "2":
int NumberOfNodes = NumberOfNodesBinaryTree(MyConnection);
if (NumberOfNodes == 0)
{
Console.Write("\n\nCreación de nodo raíz \n Escriba el valor que va a contener raiz:");
value= Console.ReadLine();
while (string.IsNullOrEmpty(value))
{
Console.Write("Ingrese un valor válido:");
value = Console.ReadLine();
}
if (InsertNewNodeBinaryTree(value.ToUpper(), 0, 0, 1,0, MyConnection) > 0)
{
Console.Write("\n\n Nodo raíz creado");
}
else
{
Console.Write("\n\n Error!!");
}
}
else if (NumberOfNodes > 0)
{
Console.Write("\n\nCreación de nodo hijo \n Escriba el número del nodo al que le quiere agregar un hijo:");
value = Console.ReadLine();
while (string.IsNullOrEmpty(value) || isIntNumber(value) == false || NodeExistBinaryTree(int.Parse(value), MyConnection)==false)
{
Console.Write("Id de nodo inexistente:");
value = Console.ReadLine();
}
List = getNodeBinaryTree(int.Parse(value),MyConnection);
SelectTypeInsertNewNodeBinaryTree(List, MyConnection);
}
else
{
Console.Write("\n\n Error!!");
}
break;
case "3":
Console.Write("\n\nEliminación de nodo \n Escriba el número del nodo que desea eliminar:");
value = Console.ReadLine();
while (string.IsNullOrEmpty(value) || isIntNumber(value) == false || NodeExistBinaryTree(int.Parse(value), MyConnection) == false)
{
Console.Write("Id de nodo inexistente:");
value = Console.ReadLine();
}
List = getNodeBinaryTree(int.Parse(value), MyConnection);
if (List[2].Equals("0") && List[3].Equals("0"))
{
DeleteNodeOrTree(int.Parse(List[0]), int.Parse(List[5]), MyConnection);
}
else
{
Console.Write("\n Imposible eliminar un nodo con hijos!! \n");
}
break;
case "4":
List = getRootNodeBinaryTree(MyConnection);
if (List != null)
{
Console.Write("\n PreOrden: ");
PreOrden(int.Parse(List[0]), MyConnection);
Console.Write("\n InOrden: ");
InOrden(int.Parse(List[0]), MyConnection);
Console.Write("\n PostOrden: ");
PostOrden(int.Parse(List[0]), MyConnection);
}
else
{
Console.Write("\n No hay nodos!! \n ");
}
break;
default:
if (!x.Equals("0")) { Console.Write("Opción invalida!! \n"); }
break;
}
} while (!x.Equals("0"));
}
public static void SelectTypeInsertNewNodeBinaryTree(string[] _list, OleDbConnection _myConnection)
{
string value=string.Empty;
string valueNode = string.Empty;
int level=0;
int identity = 0;
int fl = 0;
if (!_list[2].Equals("0") && !_list[3].Equals("0"))
{
Console.Write("\n\n El nodo " + _list[0] + " ya tiene Hijo Izquierdo e Hijo Derecho");
fl = 0;
}
else if (_list[2].Equals("0") && _list[3].Equals("0"))
{
Console.Write("\n\n Seleccionó el nodo " + _list[0] + " Seleccione nodo a agregar...\n 1) Hijo izquierdo \n 2) Hijo derecho \n 3) Ir al menú superior \n");
value = Console.ReadLine();
while (string.IsNullOrEmpty(value) || (!value.Equals("1") && !value.Equals("2") && !value.Equals("3")))
{
Console.Write("Ingrese un valor válido:");
value = Console.ReadLine();
}
fl = 1;
}
else if (!_list[2].Equals("0") && _list[3].Equals("0"))
{
Console.Write("\n\n Seleccionó el nodo " + _list[0] + " Seleccione nodo a agregar...\n 1) Hijo derecho \n 2) Ir al menú superior \n");
value = Console.ReadLine();
while (string.IsNullOrEmpty(value) || (!value.Equals("1") && !value.Equals("2")))
{
Console.Write("Ingrese un valor válido:");
value = Console.ReadLine();
}
fl = 2;
}
else if (_list[2].Equals("0") && !_list[3].Equals("0"))
{
Console.Write("\n\n Seleccionó el nodo " + _list[0] + " Seleccione nodo a agregar...\n 1) Hijo izquierdo \n 2) Ir al menú superior \n");
value = Console.ReadLine();
while (string.IsNullOrEmpty(value) || (!value.Equals("1") && !value.Equals("2")))
{
Console.Write("Ingrese un valor válido:");
value = Console.ReadLine();
}
fl = 3;
}
switch (fl)
{
case 1:
if (value.Equals("1") || value.Equals("2"))
{
Console.Write("\n Escriba el valor que va a contener el nodo:");
valueNode = Console.ReadLine();
while (string.IsNullOrEmpty(valueNode))
{
Console.Write("Ingrese un valor válido:");
valueNode = Console.ReadLine();
}
level = int.Parse(_list[4]) + 1;
identity = InsertNewNodeBinaryTree(valueNode.ToUpper(), 0, 0, level, int.Parse(_list[0]), _myConnection);
if (value.Equals("1"))
{
updateNodeBinaryTree(int.Parse(_list[0]), identity, "left", _myConnection);
}
else
{
updateNodeBinaryTree(int.Parse(_list[0]), identity, "right", _myConnection);
}
}
break;
case 2:
if (value.Equals("1"))
{
Console.Write("\n Escriba el valor que va a contener el nodo:");
valueNode = Console.ReadLine();
while (string.IsNullOrEmpty(valueNode))
{
Console.Write("Ingrese un valor válido:");
valueNode = Console.ReadLine();
}
level = int.Parse(_list[4]) + 1;
identity = InsertNewNodeBinaryTree(valueNode.ToUpper(), 0, 0, level, int.Parse(_list[0]), _myConnection);
updateNodeBinaryTree(int.Parse(_list[0]), identity, "right", _myConnection);
}
break;
case 3:
if (value.Equals("1"))
{
Console.Write("\n Escriba el valor que va a contener el nodo:");
valueNode = Console.ReadLine();
while (string.IsNullOrEmpty(valueNode))
{
Console.Write("Ingrese un valor válido:");
valueNode = Console.ReadLine();
}
level = int.Parse(_list[4]) + 1;
identity = InsertNewNodeBinaryTree(valueNode.ToUpper(), 0, 0, level, int.Parse(_list[0]), _myConnection);
updateNodeBinaryTree(int.Parse(_list[0]), identity, "left", _myConnection);
}
break;
default:
break;
}
}
public static int updateNodeBinaryTree(int _idNodeFather, int _idNodeChild, string _type, OleDbConnection _myConnection)
{
string Query = string.Empty;
int flag;
try
{
if (_type.Equals("left"))
{ Query = "update Arbol set HijoIzquierdo="+_idNodeChild+" where Id="+_idNodeFather; }
else { Query = "update Arbol set HijoDerecho=" + _idNodeChild + " where Id=" + _idNodeFather; }
OleDbCommand CommandQuery = new OleDbCommand(Query, _myConnection);
OleDbDataAdapter update = new OleDbDataAdapter();
_myConnection.Open();
update.UpdateCommand = CommandQuery;
update.UpdateCommand.ExecuteNonQuery();
_myConnection.Close();
flag = 1;
}
catch { flag = 0; _myConnection.Close(); }
return flag;
}
public static int DeleteNodeOrTree(int _idNode, int _idFatherNode, OleDbConnection _myConnection)
{
string Query = string.Empty;
string[] List = null;
int flag;
try
{
List = getNodeBinaryTree(_idFatherNode, _myConnection);
if (_idNode.Equals("-1")) { Query = "delete from Arbol"; } else { Query = "delete from Arbol where Id=" + _idNode; }
OleDbCommand CommandQuery = new OleDbCommand(Query, _myConnection);
OleDbDataAdapter delete = new OleDbDataAdapter();
_myConnection.Open();
delete.DeleteCommand = CommandQuery;
delete.DeleteCommand.ExecuteNonQuery();
_myConnection.Close();
if (List != null)
{
if (List[2].Equals(_idNode.ToString()) && !List[3].Equals(_idNode.ToString()))
{
Query = "update Arbol set HijoIzquierdo=0 where Id=" + _idFatherNode;
}
else if (!List[2].Equals(_idNode.ToString()) && List[3].Equals(_idNode.ToString()))
{
Query = "update Arbol set HijoDerecho=0 where Id=" + _idFatherNode;
}
OleDbCommand CommandQueryUpdate = new OleDbCommand(Query, _myConnection);
OleDbDataAdapter update = new OleDbDataAdapter();
_myConnection.Open();
update.UpdateCommand = CommandQueryUpdate;
update.UpdateCommand.ExecuteNonQuery();
_myConnection.Close();
}
flag = 1;
}
catch { flag = 0; _myConnection.Close(); }
return flag;
}
public static int InsertNewNodeBinaryTree(string _value, int _leftChild, int _rightChild, int _level, int _father, OleDbConnection _myConnection)
{
string Query = "insert into Arbol (Valor,HijoIzquierdo,HijoDerecho,Nivel,Padre) values ('" + _value + "'," + _leftChild + "," + _rightChild + "," + _level + "," + _father + ")";
int flag=0;
try
{
OleDbCommand CommandQuery = new OleDbCommand(Query, _myConnection);
OleDbDataAdapter add = new OleDbDataAdapter();
_myConnection.Open();
add.InsertCommand = CommandQuery;
add.InsertCommand.ExecuteNonQuery();
Query="Select @@Identity";
OleDbCommand CommandQueryIdentity = new OleDbCommand(Query, _myConnection);
OleDbDataAdapter select = new OleDbDataAdapter();
select.SelectCommand = CommandQueryIdentity;
flag = int.Parse(select.SelectCommand.ExecuteScalar().ToString());
_myConnection.Close();
}
catch { flag = 0; _myConnection.Close(); }
return flag;
}
public static void ShowBinaryTree(OleDbConnection _myConnection)
{
string Query = "Select * from Arbol order by nivel asc, id asc";
try
{
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(Query, _myConnection);
DataSet MyDataSet = new DataSet();
_myConnection.Open();
MyAdapter.Fill(MyDataSet);
if (MyDataSet.Tables[0].Rows.Count > 0)
{
Console.Write("\nId \t Valor \t Hijo Izquierdo \t Hijo Derecho \t Padre \t Nivel\n");
for (int i = 0; i < MyDataSet.Tables[0].Rows.Count; i++)
{
DataRow field = MyDataSet.Tables[0].Rows[i];
Console.Write(field["Id"].ToString() + "\t " + field["Valor"].ToString() + "\t\t" + field["HijoIzquierdo"].ToString() + "\t\t\t" + field["HijoDerecho"].ToString() + "\t " + field["Padre"].ToString() + "\t " + field["Nivel"].ToString() + "\n");
}
}
else
{
Console.Write("\n No hay nodos creados.\n");
}
_myConnection.Close();
}
catch { _myConnection.Close(); }
}
public static int NumberOfNodesBinaryTree(OleDbConnection _myConnection)
{
string Query = "select count(*) as total from Arbol";
int NumberOfNodes = -1;
try
{
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(Query, _myConnection);
DataSet MyDataSet = new DataSet();
_myConnection.Open();
MyAdapter.Fill(MyDataSet);
DataRow field = MyDataSet.Tables[0].Rows[0];
NumberOfNodes = int.Parse(field["total"].ToString());
_myConnection.Close();
}
catch { NumberOfNodes = -1; _myConnection.Close(); }
return NumberOfNodes;
}
public static bool NodeExistBinaryTree(int _idNode, OleDbConnection _myConnection)
{
string Query = "select count(*) as total from Arbol where Id="+_idNode;
bool fl= false;
int NumberOfNodes = 0;
try
{
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(Query, _myConnection);
DataSet MyDataSet = new DataSet();
_myConnection.Open();
MyAdapter.Fill(MyDataSet);
DataRow field = MyDataSet.Tables[0].Rows[0];
NumberOfNodes = int.Parse(field["total"].ToString());
_myConnection.Close();
if (NumberOfNodes == 1) { fl = true; }
}
catch { fl=false; _myConnection.Close(); }
return fl;
}
public static string[] getNodeBinaryTree(int _idNode, OleDbConnection _myConnection)
{
string Query = "Select * from Arbol where Id="+_idNode;
string[] List = null;
try
{
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(Query, _myConnection);
DataSet MyDataSet = new DataSet();
_myConnection.Open();
MyAdapter.Fill(MyDataSet);
if (MyDataSet.Tables[0].Rows.Count == 1)
{
DataRow field = MyDataSet.Tables[0].Rows[0];
List = new string[6];
List[0] = field["Id"].ToString();
List[1] = field["Valor"].ToString();
List[2] = field["HijoIzquierdo"].ToString();
List[3] = field["HijoDerecho"].ToString();
List[4] = field["Nivel"].ToString();
List[5] = field["Padre"].ToString();
}
_myConnection.Close();
}
catch { List = null; _myConnection.Close(); }
return List;
}
public static string[] getRootNodeBinaryTree( OleDbConnection _myConnection)
{
string Query = "Select * from Arbol where Padre=0";
string[] List = null;
try
{
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(Query, _myConnection);
DataSet MyDataSet = new DataSet();
_myConnection.Open();
MyAdapter.Fill(MyDataSet);
if (MyDataSet.Tables[0].Rows.Count == 1)
{
DataRow field = MyDataSet.Tables[0].Rows[0];
List = new string[6];
List[0] = field["Id"].ToString();
List[1] = field["Valor"].ToString();
List[2] = field["HijoIzquierdo"].ToString();
List[3] = field["HijoDerecho"].ToString();
List[4] = field["Nivel"].ToString();
List[5] = field["Padre"].ToString();
}
_myConnection.Close();
}
catch { List = null; _myConnection.Close(); }
return List;
}
public static bool isIntNumber(string _numberText)
{
int Result = 0;
bool numberResult = false;
if (int.TryParse(_numberText, out Result))
{
numberResult = true;
}
return numberResult;
}
public static void PreOrden(int _idNode, OleDbConnection _myConnection)
{
string[] List = null;
if (NodeExistBinaryTree(_idNode, _myConnection))
{
List = getNodeBinaryTree(_idNode, _myConnection);
Console.Write(List[1]);
PreOrden(int.Parse(List[2]), _myConnection);
PreOrden(int.Parse(List[3]), _myConnection);
}
}
public static void InOrden(int _idNode, OleDbConnection _myConnection)
{
string[] List = null;
if (NodeExistBinaryTree(_idNode, _myConnection))
{
List = getNodeBinaryTree(_idNode, _myConnection);
InOrden(int.Parse(List[2]), _myConnection);
Console.Write(List[1]);
InOrden(int.Parse(List[3]), _myConnection);
}
}
public static void PostOrden(int _idNode, OleDbConnection _myConnection)
{
string[] List = null;
if (NodeExistBinaryTree(_idNode, _myConnection))
{
List = getNodeBinaryTree(_idNode, _myConnection);
PostOrden(int.Parse(List[2]), _myConnection);
PostOrden(int.Parse(List[3]), _myConnection);
Console.Write(List[1]);
}
}
}
}
Proyecto unidad 3(maquina de dulces y refrescos)
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace Proyecto_PilasColas_Prototipo_
{
class cola
{
int[]
vec;
int p,
u, tam;
public
cola(int max)
{
tam = max;
vec = new
int[tam];
p = u = -1;
}
public int this[int v]
{
set
{ vec[v] = Convert.ToInt16(value); }
get
{ return
vec[v]; }
}
public bool esta_llena()
{
if
(u >= tam - 1)
{
return
true;
}
return
false;
}
public bool esta_vacia()
{
if
(p == -1)
{
return
true;
}
return
false;
}
public bool agregar(int
dato)
{
if (!esta_llena())
{
vec[++u] = dato;
if (u == 0)
{
p = 0;
}
return
true;
}
return
false;
}
public bool extraer(ref int dato)
{
if (!esta_vacia())
{
dato = vec[p];
if (p == u)
{
p = -1;
u = p;
}
else
{
p++;
}
return
true;
}
return
false;
}
}
}
========================================
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
namespace Proyecto_PilasColas_Prototipo_
{
class PILA<T>
{
T[] vec;
int
tam, tope, tam2, tope2;
bool vacia, llena, vacia2, llena2;
public PILA(int n)
{
tam = n;
vec = new
T[tam];
tope = 0;
vacia = true;
llena = false;
vacia2 = true;
llena2 = false;
tam2 = n;
tope2 = 0;
}
public void Push(T valor)
{
vacia = false;
vec[tope++] = valor;
if (tope == tam)
llena = true;
}
public void Push2(T valor)
{
vacia2 = false;
vec[tope2++] = valor;
if (tope2 == tam2)
llena2 = true;
}
public
T Pop()
{
if
(--tope == 0)
vacia = true;
llena = false;
return
vec[tope];
}
public
T Pop2()
{
if
(--tope2 == 0)
vacia2 = true;
llena2 = false;
return vec[tope2];
}
public bool EstaVacia
{
get {
return vacia; }
}
public bool
EstaVacia2
{
get { return vacia2;
}
}
public bool EstaLlena
{
get
{ return llena; }
}
public bool EstaLlena2
{
get
{ return llena2; }
}
public
T Tope
{
get
{ return vec[tope - 1]; }
}
}
}
================================
using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
namespace
Proyecto_PilasColas_Prototipo_
{
public partial class Form1 : Form
{
PILA<string> p;
cola col;
int refrescos = 10;
int clientes = 5;
int dulces = 10;
int
cont1 = 0;
int
cont2 = 0;
string
ex = "";
string
res = "";
string
c = "";
int re,
rc, dul, dulc, cc, cr;
public
Form1()
{
InitializeComponent();
}
private
void butComprar1_Click(object
sender, EventArgs e)
{
if
(!p.EstaVacia)
{
label2.Text += Convert.ToString(dataGridView1[0, re - (dulces +
1)].Value) + " ";
p.Pop();
dataGridView1[0, re - (dulces +
1)].Value = " ";
dulces++;
cont1++;
}
else
{
MessageBox.Show("LA PILA ESTA VACIA");
}
}
private
void butComprar2_Click(object
sender, EventArgs e)
{
if
(!p.EstaVacia2)
{
label1.Text += Convert.ToString(dataGridView3[0, dul - (refrescos
+ 1)].Value) + " ";
p.Pop2();
dataGridView3[0, dul -
(refrescos + 1)].Value = " ";
refrescos++;
cont2++;
}
else
{
MessageBox.Show("LA PILA ESTA VACIA");
}
}
private void
butRellenarMaqDul_Click(object sender, EventArgs e)
{
if
(!p.EstaLlena)
{
ex = Convert.ToString("CHOCOLATES");
dataGridView1[0, re -
dulces].Value = ex;
dulces--;
p.Push(ex);
}
else
{
MessageBox.Show("LA PILA ESTA LLENA");
}
}
private
void butRellenarRefrescos_Click(object sender, EventArgs
e)
{
if
(!p.EstaLlena2)
{
res = Convert.ToString("COCA");
dataGridView3[0, re -
refrescos].Value = res;
refrescos--;
p.Push2(res);
}
else
{
MessageBox.Show("LA PILA
ESTA LLENA");
}
}
private
void butClientes_Click(object
sender, EventArgs e)
{
if
(col.agregar(clientes + cc))
{
c = Convert.ToString("CLIENTE");
dataGridView2[cc - clientes, 0].Value = c;
clientes--;
}
else
{
MessageBox.Show("DESBORDAMIENTO COLA LLENA");
}
butComprar1.Enabled = true;
butRellenarMaqDul.Enabled = true;
butComprar2.Enabled = true;
butRellenarRefrescos.Enabled = true;
dataGridView1.Visible = true;
dataGridView3.Visible = true;
}
private
void butSalir_Click(object
sender, EventArgs e)
{
Close();
}
private
void butIniciar_Click(object
sender, EventArgs e)
{
butComprar1.Enabled = false;
butRellenarMaqDul.Enabled = false;
butComprar2.Enabled = false;
butRellenarRefrescos.Enabled = false;
re = 10;
rc = 1;
dul = 10;
dulc = 1;
cc = 5;
cr = 1;
dataGridView2.RowCount = cr;
dataGridView2.ColumnCount = cc;
dataGridView3.RowCount = re;
dataGridView3.ColumnCount = rc;
dataGridView1.RowCount = dul;
dataGridView1.ColumnCount = dulc;
dataGridView1.Visible = false;
dataGridView3.Visible = false;
p = new
PILA<string>(10);
col = new
cola(5);//clientes
}
private
void butExtraer_Click(object
sender, EventArgs e)
{
try
{
label3.Text += ((cont1 * (Convert.ToInt32(7))) + (cont2 * Convert.ToInt32(9))) + ".00";
label3.Visible = true;
MessageBox.Show(" nueva compra" + " cliente extraido");
label2.Text = "";
label3.Text = "";
int d = 0;
if
(col.extraer(ref d))
{
dataGridView2[cc -
(clientes + 5), 0].Value = "";
clientes--;
}
else
{
MessageBox.Show("DESBORDAMIENTO COLA VACIA");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private
void butPagar_Click(object
sender, EventArgs e)
{
try
{
int
d = 0;
if
(col.extraer(ref d))
{
dataGridView2[cc -
(clientes + 5), 0].Value = "";
clientes--;
}
else
{
MessageBox.Show("DESBORDAMIENTO COLA VACIA");
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void
butAcercaDe_Click(object sender, EventArgs e)
{
Form2
aux = new Form2();
aux.Show();
}
}
}
Suscribirse a:
Entradas (Atom)