Reading a txt file, split string then write to txt file - c#

I have a text file call groceries. That contain text similar to the following:
regular,cereal,4.00,1;
fresh,rump steak,11.99,0.8;
The code below is trying to read the text file, split the string and then write to a text file called invoice.
The invoice text file should read read line in the groceries file, list whether it is a "fresh" or "regular" grocery item. If fresh GST is not applied if regular GST is applied. Calculate the cost on weight for fresh and quantity for regular and then display a total cost of items listed.
Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines ("Groceries.txt");
File.WriteAllLines("Invoice.txt", invoices.ToArray());
List<string> invoices = new List<string>();
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = "fresh";
freshGrocery.Price = 30;
freshGrocery.Weight = 0.5;
Grocery grocery = new Grocery();
grocery.Name = "regular";
grocery.Price = 50;
grocery.Quantity = 2;
double price = price.Calculate();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
invoices.Add(counter + "," + grocery + price+Quantity+"," + DateTime.Now.Date);
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}

try something like that
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Groceries3
{
class Program
{
static void Main(string[] args)
{
string[] groceries = File.ReadAllLines("Groceries.txt");
List<string> invoices = new List<string>();
int counter = 0;
foreach (var grocery2 in groceries)
{
counter++;
var list = grocery2.Split(',');
if (list[0].Equals("fresh"))
{
FreshGrocery freshGrocery = new FreshGrocery();
freshGrocery.Name = list[1];
freshGrocery.Price = double.Parse(list[2]);
freshGrocery.Weight = double.Parse(list[3].Replace(";", ""));
invoices.Add(counter + "," + freshGrocery.Name + "," + freshGrocery.Price + "," + freshGrocery.Weight + "," + DateTime.Now.Date);
}
else if (list[0].Equals("regular"))
{
Grocery grocery = new Grocery();
grocery.Name = list[1];
grocery.Price = double.Parse(list[2]);
grocery.Quantity = int.Parse(list[3].Replace(";", ""));
double price = grocery.Calculate();
invoices.Add(counter + "," + grocery.Name + "," + price + "," + grocery.Quantity + "," + DateTime.Now.Date);
}
}
File.WriteAllLines("Invoice.txt", invoices.ToArray());
}
abstract class GroceryItem
{
private string name;
private double price = 0;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public double Price
{
get
{
return price;
}
set
{
price = value;
}
}
public abstract double Calculate();
}
class FreshGrocery : GroceryItem
{
private double weight = 0;
public double Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}
public override double Calculate()
{
return this.Price * this.weight;
}
}
class Grocery : GroceryItem
{
private int quantity = 0;
private double gst = 10;
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
}
}
public override double Calculate()
{
double calculatedPrice = this.Price * this.Quantity;
if (calculatedPrice < 0)
{
calculatedPrice += calculatedPrice * (gst / 100);
}
return calculatedPrice;
}
}
class ShoppingCart
{
private List<GroceryItem> orders;
public List<GroceryItem> Orders
{
get
{
return orders;
}
set
{
orders = value;
}
}
public double Calculate()
{
double price = 0;
if (this.Orders != null)
{
foreach (GroceryItem order in this.Orders)
{
price += order.Calculate();
}
}
return price;
}
}
}
}

Related

Using keyword "value" in set accessor C#

I'm trying to use the keyword value in the set accessor and as long as the user entered value is greater than 0, I want to set it to the variable Quantity.
I can not seem to find what it is I am doing wrong. I keep getting a traceback error to for this Quantity = value;. Hoping someone can see what I don't. Thanks.
using System;
namespace Invoice
{
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("How many parts would you like to " +
"enter into the system: ");
int newParts = int.Parse(Console.ReadLine());
Invoice[] invoice = new Invoice[newParts];
for (int i = 0; i < newParts; i++)
{
invoice[i] = new Invoice();
Console.WriteLine("Enter the part number: ");
invoice[i].PartNumber = Console.ReadLine();
Console.WriteLine("Enter description of item: ");
invoice[i].PartDescription = Console.ReadLine();
Console.WriteLine("Enter the quantity: ");
invoice[i].Quantity = int.Parse(Console.ReadLine());
Console.WriteLine("Enter in the price of the item: ");
invoice[i].PricePerItem = decimal.Parse(Console.ReadLine());
}
for (int i = 0; i < newParts; i++)
{
invoice[i].DisplayOrder();
}
}
}
}
using System;
namespace Invoice
{
public class Invoice
{
public string PartNumber { get; set; }
public string PartDescription { get; set; }
public int Quantity
{
get { return Quantity; }
set
{
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
}
}
public decimal PricePerItem
{
get
{
return PricePerItem;
}
set
{
if(value >= 0.0m)
{
PricePerItem = value;
}
if (value <= 0.0m)
{
PricePerItem = PricePerItem;
}
}
}
public Invoice(String PartNumber, String PartDescription, int Quantity, decimal PricePerItem)
{
this.PartNumber = PartNumber;
this.PartDescription = PartDescription;
this.Quantity = Quantity;
this.PricePerItem = PricePerItem;
}
public Invoice()
{
}
public decimal GetInvoiceAmount(int numberOfItems, decimal priceOfItem)
{
return numberOfItems * priceOfItem;
}
public void DisplayOrder()
{
decimal total = GetInvoiceAmount(Quantity, PricePerItem);
// Display Receipt
Console.Write("\nOrder Receipt: ");
Console.WriteLine($"\nPart Number: {PartNumber}");
Console.WriteLine($"Unit Price: {PricePerItem:C}");
Console.WriteLine($"Quantity: {Quantity}");
Console.WriteLine($"Part Description: {PartDescription}");
Console.WriteLine($"Total price: {total:C}");
}
}
}
This makes no sense:
if (value >= 0)
{
Quantity = value;
}
if (value <= 0)
{
Quantity = Quantity;
}
Why would you set a property to itself? That can't achieve anything useful. You say that you want to set the property if and only if the assigned value is greater than zero, so why would you be checking value for anything but being greater than zero?
if (value > 0)
{
Quantity = value;
}
That's it, that's all.
That said, you also ought to be throwing an ArgumentOutOfRangeException if the value is not valid, rather than just silently not setting the property. The logical way to do that would be like so:
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
Quantity = value;
Now the property value will only be set if an exception is not thrown.
I also just realised that you have no backing field for this property, so that's wrong. The whole thing should look like this:
private int quantity;
public int Quantity
{
get { return quantity; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(...);
}
quantity = value;
}
}
The error is because in your set {} you are invoking the same setter recursively.
private int quantity;
public int Quantity
{
get { return this.quantity; }
set
{
if (value >= 0)
{
this.quantity= value;
}
}
}
private decimal pricePerItem;
public decimal PricePerItem
{
get
{
return this.pricePerItem;
}
set
{
if(value >= 0.0m)
{
this.pricePerItem= value;
}
}
}

Delete function for simple inventory

I have a simple inventory application which is a program which you can add, view and delete the product. Currently I had already finished the add function and view function but left only the delete function which I am unsure of. ( Main program case 3)
class Inventory
{
Product []items;
int maxSize;
int size;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
size = 0;
items = new Product[maxSize];
}
public bool AddProduct(Product in_Product)
{
if(getSize()<maxSize)
{
items[size] = in_Product;
size++;
return true;
}
else
{
return false;
}
}
public int getSize()
{
return size;
}
public Product getProduct(int index)
{
return items[index];
}
}
}
here is my product class:
class Product
{
private string name;
private int itemNumber;
private int unitsInStock;
private double price;
private double value;
public Product()
{
}
public Product(string in_name, int in_itemNumber, int in_unitsInStock, double in_price)
{
name = in_name;
itemNumber = in_itemNumber;
unitsInStock = in_unitsInStock;
price = in_price;
}
public double getValueOfInventory()
{
value = unitsInStock * price;
return this.value;
}
public int getItemNumber()
{
return this.itemNumber;
}
public string getName()
{
return this.name;
}
public int getUnitsInStock()
{
return this.unitsInStock;
}
public double getPrice()
{
return this.price;
}
public void setItemNumber(int in_itemNumber)
{
itemNumber = in_itemNumber;
}
public void setName(string in_name)
{
name = in_name;
}
public void setUnitsInStock(int in_unitsInStock)
{
unitsInStock = in_unitsInStock;
}
public void setPrice(double in_price)
{
price = in_price;
}
}
}
Here is my main program:
class Program
{
static void Main(string[] args)
{
Inventory myInventory = new Inventory(100);
Product myProduct = new Product();
myProduct.setItemNumber(1000);
myProduct.setName("Pen");
myProduct.setPrice(1.25);
myProduct.setUnitsInStock(50);
myInventory.AddProduct(myProduct);
Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
myInventory.AddProduct(myProduct1);
Product tempProduct;
int x = 0;
do
{
Console.WriteLine("1.Add product");
Console.WriteLine("2.View product");
Console.WriteLine("3.Delete product");
Console.WriteLine("4.Exit the Application");
Console.WriteLine("------------------");
x = Convert.ToInt32(Console.ReadLine());
switch (x)
{
case 1:
Console.Write("Item number\t\t:");
int a=Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
string b=Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
double c=Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
int d=Convert.ToInt32(Console.ReadLine());
Product myProduct2 = new Product(b,a,d,c);
myInventory.AddProduct(myProduct2);
// Product myProduct1 = new Product("Paper", 2000, 5000, 12.85);
// myInventory.AddProduct(myProduct1);
/*Console.Write("Item number\t\t:");
ItemNo = Convert.ToInt32(Console.ReadLine());
Console.Write("Name\t\t\t:");
Name = Convert.ToString(Console.ReadLine());
Console.Write("Price\t\t\t:");
Price = Convert.ToDouble(Console.ReadLine());
Console.Write("Units in stocks\t\t:");
UnitsInStocks = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("------------------");*/
break;
case 2:
for (int i = 0; i < myInventory.getSize(); i++)
{
tempProduct = myInventory.getProduct(i);
Console.WriteLine("Item number\t\t:" + tempProduct.getItemNumber());
Console.WriteLine("Name\t\t\t:" + tempProduct.getName());
Console.WriteLine("Price\t\t\t:" + tempProduct.getPrice());
Console.WriteLine("Units in stocks\t\t:" + tempProduct.getUnitsInStock());
Console.WriteLine("------------------");
}
break;
case 3:
int j;
Console.WriteLine("Please enter the item id for the items that you want to delete");
j = Convert.ToInt32(Console.ReadLine());
if (j == a)
{
break;
case 4:
Environment.Exit(0);
break;
default:
break;
}
}
while (x != 4);
}
}
}
In my main program, i left case 3 undone as that is the delete function part,
How can I accomplish this?
This is the simple way. Replace your array with a List of products:
class Inventory
{
List<Product> items;
int maxSize;
public Inventory(int in_maxSize)
{
maxSize = in_maxSize;
items = new List<Product>();
}
public bool AddProduct(Product in_Product)
{
if(items.Count < maxSize)
{
items.Add(in_Product);
return true;
}
else
{
return false;
}
}
public Product getProduct(int index)
{
return items[index];
}
public void removeProduct(int index)
{
items.removeAt(index);
}
}
In your switch call removeProduct method to delete the product at position that you pass.

Using Neural Network to solve Y = X * X + b type formula

Update 1/6/2014: I've updated the question so that I'm trying to solve a non-linear equation. As many of you pointed out I didn't need the extra complexity (hidden-layer, sigmoid function, etc) in order to solve a non-linear problem.
Also, I realize I could probably solve even non-linear problems like this using other means besides neural networks. I'm not trying to write the most efficient code or the least amount of code. This is purely for me to better learn neural networks.
I've created my own implementation of back propagated neural network.
It is working fine when trained to solve simple XOR operations.
However now I want to adapt it & train it to solve Y = X * X + B type formulas, but I'm not getting expected results. After training the network does not calculate the correct answers. Are neural networks well-suited for solving algebra equations like this? I realize my example is trivial I'm just trying to learn more about neural networks and their capabilities.
My hidden layer is using a sigmoid activation function and my output layer is using an identity function.
If you could analyze my code and point out any errors I'd be grateful.
Here is my full code (C# .NET):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NeuralNetwork
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Training Network...");
Random r = new Random();
var network = new NeuralNetwork(1, 5, 1);
for (int i = 0; i < 100000; i++)
{
int x = i % 15;
int y = x * x + 10;
network.Train(x);
network.BackPropagate(y);
}
//Below should output 20, but instead outputs garbage
Console.WriteLine("0 * 0 + 10 = " + network.Compute(0)[0]);
//Below should output 110, but instead outputs garbage
Console.WriteLine("10 * 10 + 10 = " + network.Compute(10)[0]);
//Below should output 410, but instead outputs garbage
Console.WriteLine("20 * 20 + 10 = " + network.Compute(20)[0]);
}
}
public class NeuralNetwork
{
public double LearnRate { get; set; }
public double Momentum { get; set; }
public List<Neuron> InputLayer { get; set; }
public List<Neuron> HiddenLayer { get; set; }
public List<Neuron> OutputLayer { get; set; }
static Random random = new Random();
public NeuralNetwork(int inputSize, int hiddenSize, int outputSize)
{
LearnRate = .9;
Momentum = .04;
InputLayer = new List<Neuron>();
HiddenLayer = new List<Neuron>();
OutputLayer = new List<Neuron>();
for (int i = 0; i < inputSize; i++)
InputLayer.Add(new Neuron());
for (int i = 0; i < hiddenSize; i++)
HiddenLayer.Add(new Neuron(InputLayer));
for (int i = 0; i < outputSize; i++)
OutputLayer.Add(new Neuron(HiddenLayer));
}
public void Train(params double[] inputs)
{
int i = 0;
InputLayer.ForEach(a => a.Value = inputs[i++]);
HiddenLayer.ForEach(a => a.CalculateValue());
OutputLayer.ForEach(a => a.CalculateValue());
}
public double[] Compute(params double[] inputs)
{
Train(inputs);
return OutputLayer.Select(a => a.Value).ToArray();
}
public double CalculateError(params double[] targets)
{
int i = 0;
return OutputLayer.Sum(a => Math.Abs(a.CalculateError(targets[i++])));
}
public void BackPropagate(params double[] targets)
{
int i = 0;
OutputLayer.ForEach(a => a.CalculateGradient(targets[i++]));
HiddenLayer.ForEach(a => a.CalculateGradient());
HiddenLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
OutputLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
}
public static double NextRandom()
{
return 2 * random.NextDouble() - 1;
}
public static double SigmoidFunction(double x)
{
if (x < -45.0) return 0.0;
else if (x > 45.0) return 1.0;
return 1.0 / (1.0 + Math.Exp(-x));
}
public static double SigmoidDerivative(double f)
{
return f * (1 - f);
}
public static double HyperTanFunction(double x)
{
if (x < -10.0) return -1.0;
else if (x > 10.0) return 1.0;
else return Math.Tanh(x);
}
public static double HyperTanDerivative(double f)
{
return (1 - f) * (1 + f);
}
public static double IdentityFunction(double x)
{
return x;
}
public static double IdentityDerivative()
{
return 1;
}
}
public class Neuron
{
public bool IsInput { get { return InputSynapses.Count == 0; } }
public bool IsHidden { get { return InputSynapses.Count != 0 && OutputSynapses.Count != 0; } }
public bool IsOutput { get { return OutputSynapses.Count == 0; } }
public List<Synapse> InputSynapses { get; set; }
public List<Synapse> OutputSynapses { get; set; }
public double Bias { get; set; }
public double BiasDelta { get; set; }
public double Gradient { get; set; }
public double Value { get; set; }
public Neuron()
{
InputSynapses = new List<Synapse>();
OutputSynapses = new List<Synapse>();
Bias = NeuralNetwork.NextRandom();
}
public Neuron(List<Neuron> inputNeurons) : this()
{
foreach (var inputNeuron in inputNeurons)
{
var synapse = new Synapse(inputNeuron, this);
inputNeuron.OutputSynapses.Add(synapse);
InputSynapses.Add(synapse);
}
}
public virtual double CalculateValue()
{
var d = InputSynapses.Sum(a => a.Weight * a.InputNeuron.Value) + Bias;
return Value = IsHidden ? NeuralNetwork.SigmoidFunction(d) : NeuralNetwork.IdentityFunction(d);
}
public virtual double CalculateDerivative()
{
var d = Value;
return IsHidden ? NeuralNetwork.SigmoidDerivative(d) : NeuralNetwork.IdentityDerivative();
}
public double CalculateError(double target)
{
return target - Value;
}
public double CalculateGradient(double target)
{
return Gradient = CalculateError(target) * CalculateDerivative();
}
public double CalculateGradient()
{
return Gradient = OutputSynapses.Sum(a => a.OutputNeuron.Gradient * a.Weight) * CalculateDerivative();
}
public void UpdateWeights(double learnRate, double momentum)
{
var prevDelta = BiasDelta;
BiasDelta = learnRate * Gradient; // * 1
Bias += BiasDelta + momentum * prevDelta;
foreach (var s in InputSynapses)
{
prevDelta = s.WeightDelta;
s.WeightDelta = learnRate * Gradient * s.InputNeuron.Value;
s.Weight += s.WeightDelta + momentum * prevDelta;
}
}
}
public class Synapse
{
public Neuron InputNeuron { get; set; }
public Neuron OutputNeuron { get; set; }
public double Weight { get; set; }
public double WeightDelta { get; set; }
public Synapse(Neuron inputNeuron, Neuron outputNeuron)
{
InputNeuron = inputNeuron;
OutputNeuron = outputNeuron;
Weight = NeuralNetwork.NextRandom();
}
}
}
you use sigmoid as output funnction which in in the range [0-1]
but you target value is double the range is [ 0 - MAX_INT ], i think it is the basic resaon why you are getting NAN。
i update you code , and try to normalize the value in the range in [0-1],
and I can get ouptut like this which is what I expect
I think I am getting close to the truth,I am not sure why this answer is getting vote down
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NeuralNetwork
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Training Network...");
Random r = new Random();
var network = new NeuralNetwork(1, 3, 1);
for (int k = 0; k < 60; k++)
{
for (int i = 0; i < 1000; i++)
{
double x = i / 1000.0;// r.Next();
double y = 3 * x;
network.Train(x);
network.BackPropagate(y);
}
double output = network.Compute(0.2)[0];
Console.WriteLine(output);
}
//Below should output 10, but instead outputs either a very large number or NaN
/* double output = network.Compute(3)[0];
Console.WriteLine(output);*/
}
}
public class NeuralNetwork
{
public double LearnRate { get; set; }
public double Momentum { get; set; }
public List<Neuron> InputLayer { get; set; }
public List<Neuron> HiddenLayer { get; set; }
public List<Neuron> OutputLayer { get; set; }
static Random random = new Random();
public NeuralNetwork(int inputSize, int hiddenSize, int outputSize)
{
LearnRate = .2;
Momentum = .04;
InputLayer = new List<Neuron>();
HiddenLayer = new List<Neuron>();
OutputLayer = new List<Neuron>();
for (int i = 0; i < inputSize; i++)
InputLayer.Add(new Neuron());
for (int i = 0; i < hiddenSize; i++)
HiddenLayer.Add(new Neuron(InputLayer));
for (int i = 0; i < outputSize; i++)
OutputLayer.Add(new Neuron(HiddenLayer));
}
public void Train(params double[] inputs)
{
int i = 0;
InputLayer.ForEach(a => a.Value = inputs[i++]);
HiddenLayer.ForEach(a => a.CalculateValue());
OutputLayer.ForEach(a => a.CalculateValue());
}
public double[] Compute(params double[] inputs)
{
Train(inputs);
return OutputLayer.Select(a => a.Value).ToArray();
}
public double CalculateError(params double[] targets)
{
int i = 0;
return OutputLayer.Sum(a => Math.Abs(a.CalculateError(targets[i++])));
}
public void BackPropagate(params double[] targets)
{
int i = 0;
OutputLayer.ForEach(a => a.CalculateGradient(targets[i++]));
HiddenLayer.ForEach(a => a.CalculateGradient());
HiddenLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
OutputLayer.ForEach(a => a.UpdateWeights(LearnRate, Momentum));
}
public static double NextRandom()
{
return 2 * random.NextDouble() - 1;
}
public static double SigmoidFunction(double x)
{
if (x < -45.0)
{
return 0.0;
}
else if (x > 45.0)
{
return 1.0;
}
return 1.0 / (1.0 + Math.Exp(-x));
}
public static double SigmoidDerivative(double f)
{
return f * (1 - f);
}
public static double HyperTanFunction(double x)
{
if (x < -10.0) return -1.0;
else if (x > 10.0) return 1.0;
else return Math.Tanh(x);
}
public static double HyperTanDerivative(double f)
{
return (1 - f) * (1 + f);
}
public static double IdentityFunction(double x)
{
return x;
}
public static double IdentityDerivative()
{
return 1;
}
}
public class Neuron
{
public bool IsInput { get { return InputSynapses.Count == 0; } }
public bool IsHidden { get { return InputSynapses.Count != 0 && OutputSynapses.Count != 0; } }
public bool IsOutput { get { return OutputSynapses.Count == 0; } }
public List<Synapse> InputSynapses { get; set; }
public List<Synapse> OutputSynapses { get; set; }
public double Bias { get; set; }
public double BiasDelta { get; set; }
public double Gradient { get; set; }
public double Value { get; set; }
public Neuron()
{
InputSynapses = new List<Synapse>();
OutputSynapses = new List<Synapse>();
Bias = NeuralNetwork.NextRandom();
}
public Neuron(List<Neuron> inputNeurons)
: this()
{
foreach (var inputNeuron in inputNeurons)
{
var synapse = new Synapse(inputNeuron, this);
inputNeuron.OutputSynapses.Add(synapse);
InputSynapses.Add(synapse);
}
}
public virtual double CalculateValue()
{
var d = InputSynapses.Sum(a => a.Weight * a.InputNeuron.Value);// + Bias;
return Value = IsHidden ? NeuralNetwork.SigmoidFunction(d) : NeuralNetwork.IdentityFunction(d);
}
public virtual double CalculateDerivative()
{
var d = Value;
return IsHidden ? NeuralNetwork.SigmoidDerivative(d) : NeuralNetwork.IdentityDerivative();
}
public double CalculateError(double target)
{
return target - Value;
}
public double CalculateGradient(double target)
{
return Gradient = CalculateError(target) * CalculateDerivative();
}
public double CalculateGradient()
{
return Gradient = OutputSynapses.Sum(a => a.OutputNeuron.Gradient * a.Weight) * CalculateDerivative();
}
public void UpdateWeights(double learnRate, double momentum)
{
var prevDelta = BiasDelta;
BiasDelta = learnRate * Gradient; // * 1
Bias += BiasDelta + momentum * prevDelta;
foreach (var s in InputSynapses)
{
prevDelta = s.WeightDelta;
s.WeightDelta = learnRate * Gradient * s.InputNeuron.Value;
s.Weight += s.WeightDelta; //;+ momentum * prevDelta;
}
}
}
public class Synapse
{
public Neuron InputNeuron { get; set; }
public Neuron OutputNeuron { get; set; }
public double Weight { get; set; }
public double WeightDelta { get; set; }
public Synapse(Neuron inputNeuron, Neuron outputNeuron)
{
InputNeuron = inputNeuron;
OutputNeuron = outputNeuron;
Weight = NeuralNetwork.NextRandom();
}
}
}
You really don't need to use a multi-layer network to solve problems of ax + b = y. A single layer perceptron would do the trick.
In fact, for a problem this simple you don't even need to break out the complexity of a real neural network. Check out this blog post:
http://dynamicnotions.blogspot.co.uk/2009/05/linear-regression-in-c.html
I did not analyze your code, it is far too long. But I can give you the answer for the basic question:
Yes, neural networks are well suited for such problems.
In fact, for a f : R -> R in the form of ax+b=y you should use one neuron with linear activation function. No three-layered structure is required, just one neuron is enough. If your code fails in such case, then you have an implementation error, as it is a simple linear regression task solved using gradient descent.

Sorting array in ascending order error

My code below works fine but what I want to do is to display the summary in ascending order according to its OrderNum. I tried to put Array.Sort(order[x].OrderNum) but error cannot convert from int to System.Array. Any suggestions on how I can sort this? Thank you very much!
using System;
class ShippedOrder
{
public static void Main()
{
Order[] order = new Order[5];
int x, y;
double grandTotal = 0;
bool goodNum;
for (x = 0; x < order.Length; ++x)
{
order[x] = new Order();
Console.Write("Enter order number: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y < x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
while (!goodNum)
{
Console.Write("Sorry, the order number " + order[x].OrderNum + " is a duplicate. " + "\nPlease re-enter: ");
order[x].OrderNum = Convert.ToInt32(Console.ReadLine());
goodNum = true;
for (y = 0; y > x; ++y)
{
if (order[x].Equals(order[y]))
goodNum = false;
}
}
Console.Write("Enter customer name: ");
order[x].Customer = Console.ReadLine();
Console.Write("Enter Quantity: ");
order[x].Quantity = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\nSummary:\n");
for (x = 0; x < order.Length; ++x)
{
Array.Sort(order[x].OrderNum); //This line is where the error is located
Console.WriteLine(order[x].ToString());
grandTotal += order[x].Total;
}
Console.WriteLine("\nTotal for all orders is Php" + grandTotal.ToString("0.00"));
Console.Read();
}
public class Order
{
public int orderNum;
public string cusName;
public int quantity;
public double total;
public const double ItemPrice = 19.95;
public Order() { }
public Order(int ordNum, string cusName, int numOrdered)
{
OrderNum = ordNum;
Customer = cusName;
Quantity = numOrdered;
}
public int OrderNum
{
get { return orderNum; }
set { orderNum = value; }
}
public string Customer
{
get { return cusName; }
set { cusName = value; }
}
public int Quantity
{
get
{
return quantity;
}
set
{
quantity = value;
total = quantity * ItemPrice + 4;
}
}
public double Total
{
get
{
return total;
}
}
public override string ToString()
{
return ("ShippedOrder " + OrderNum + " " + Customer + " " + Quantity +
" #Php" + ItemPrice.ToString("0.00") + " each. " + "Shipping is Php4.00\n" + " The total is Php" + Total.ToString("0.00"));
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (OrderNum == temp.OrderNum)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return OrderNum;
}
}
}
Just use Linq:
order = order.OrderBy(x => x.OrderNum).ToArray();
While looking this link, found that Array.Sort will not take integer as parameter.
You have to pass all the data as Array object.
Try the following:
order.Sort( delegate (Order o1, Order o2) {
return o1.OrderNum.CompareTo(o2.OrderNum);
});

C# listbox filling textboxes by clicking on an item

I am having some issues with listbox, have been trying to make it so that when I click on an item it will populate textboxes(picture below) with information from that item.
http://i.stack.imgur.com/G32uq.jpg (wont let me post pictures).
Heres my code (This code I have currently will populate the text boxes with what I need, but I want it to be able to do the same by clicking the items).
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;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private int index;
private const int SIZE = 4;
private int count = 0;
private Employee[] employees = new Employee[SIZE];
List<Employee> listEmp = new List<Employee>(SIZE);
public Form1()
{
InitializeComponent();
listEmp.Add(new Hourly(1, "Karl", "lane drive", "201-9090", 40, 12.00)); //item1
listEmp.Add(new Salaried(2, "Steve", "circle road", "803-1230", 1200)); // item2
listEmp.Add(new Hourly(3, "Westley", "square alley", "892-2000", 40, 10.00)); //item3
listEmp.Add(new Salaried(4, "Anders", "triangle boulevard", "910-8765", 1000)); //item4
index = 0;
computPayBtn.Enabled = true;
listBox1.DataSource = listEmp;
}
// opens a file and reads data into the employee objects
private void openToolStripMenuItem1_Click(object sender, EventArgs e)
{
Stream myStream = null;
Employee tempEmploy = null;
string type = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "text files (*.txt)|*txt";
count = 0;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
StreamReader data = new StreamReader(myStream);
do
{
type = data.ReadLine();
if (type != null)
{
if (type == "hourly")
tempEmploy = new Hourly();
else if (type == "salaried")
tempEmploy = new Salaried();
tempEmploy.ReadData(data);
employees[count++] = tempEmploy;
}
} while (type != null);
computPayBtn.Enabled = true;
count = 0;
}
}
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
// shows next employee when clicked.
private void computPayBtn_Click_1(object sender, EventArgs e)
{
checkbox.Clear( );
int index = count;
if (index < SIZE)
{
string emp = "Fluffshuffle Electronics check no. ";
emp += string.Format("{0}", index);
emp += Environment.NewLine;
emp += Environment.NewLine;
emp += " Pay to the order of ";
emp += employees[index].Name;
emp += Environment.NewLine;
emp += " ";
emp += string.Format("{0:C}", employees[index].CalcPay());
emp += Environment.NewLine;
emp += Environment.NewLine;
emp += " First National Bank";
checkbox.Text = emp;
namebox.Text = employees[index].Name;
addressbox.Text = employees[index].Address;
phonebox.Text = employees[index].PhoneNum;
empNumbox.Text = string.Format("{0}", employees[index].EmpNum);
Hourly houremploy = employees[index] as Hourly;
if (houremploy != null)
{
hoursbox.Text = string.Format("{0:F2}", houremploy.HoursWorked);
wagebox.Text = string.Format("{0:F2}", houremploy.HourlyWage);
salarybox.Clear();
}
Salaried salemploy = employees[index] as Salaried;
if (salemploy != null)
{
hoursbox.Clear();
wagebox.Clear();
salarybox.Text = string.Format("{0:F2}", salemploy.Salary);
}
count++;
}
else
{
computPayBtn.Enabled = false;
namebox.Clear( );
addressbox.Clear(); ;
phonebox.Clear(); ;
empNumbox.Clear( );
hoursbox.Clear();
wagebox.Clear();
salarybox.Clear();
count = 0;
}
}
// saves employee objects into a txt file.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream = null;
count = SIZE;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = "c:\\";
saveFileDialog.Filter = "text files (*.txt)|*txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog.OpenFile()) != null)
{
StreamWriter data = new StreamWriter(myStream);
for (int i = 0; i < count; i++)
{
employees[i].WriteData(data);
employees[i] = null;
}
data.Close();
computPayBtn.Enabled = false;
count = 0;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
And the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
// provides methods to read and write objects to a file
public interface IStorable
{
// writes object's data to a StreamWriter object
// The StreamReader object to write to
void WriteData(StreamWriter swo);
// reads object's data from a StreamReader object
// The StreamReader object to read from
void ReadData(StreamReader sro);
}
public abstract class Employee : IStorable
{
private int empNum;
private string name;
private string address;
private string phoneNum;
protected const double STATE_TAX = 0.075;
protected const double FED_TAX = 0.20;
// set data members to defaults
public Employee()
{
empNum = 0;
name = "unknown";
address = "unknown";
phoneNum = "unknown";
}
// set data members to values passed to method
// employee number, name, address, and phone number
public Employee(int _empNum, string _name, string _address, string _phoneNum)
{
empNum = _empNum;
name = _name;
address = _address;
phoneNum = _phoneNum;
}
public int EmpNum
{
get { return empNum; }
set { empNum = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public string Address
{
get { return address; }
set { address = value; }
}
public string PhoneNum
{
get { return phoneNum; }
set { phoneNum = value; }
}
// reads object's data from a StreamReader object
// The method is virtual so we can use polymorphism
public virtual void ReadData(StreamReader sro)
{
EmpNum = int.Parse(sro.ReadLine());
Name = sro.ReadLine();
Address = sro.ReadLine();
PhoneNum = sro.ReadLine();
}
// writes object's data to a StreamReader object
// The method is virtual so we can use polymorphism
public virtual void WriteData(StreamWriter sro)
{
sro.WriteLine(this.EmpNum);
sro.WriteLine(this.Name);
sro.WriteLine(this.Address);
sro.WriteLine(this.PhoneNum);
}
// calculates the employee's net pay
public abstract double CalcPay();
}
// The Hourly Class - represents an hourly employee
// Inherits from Employee
class Hourly : Employee
{
private const int WEEK = 40;
private const double BONUS = 1.5;
private double hoursWorked;
private double hourlyWage;
//set data members to defaults
public Hourly()
{
hoursWorked = 0.0;
hourlyWage = 0.0;
}
// set data members to values passed as arguments
// employee number, name, address, phone number, hours, and wage
public Hourly(int _empNum, string _name, string _address, string _phoneNum, double _hours, double _wage)
: base(_empNum, _name, _address, _phoneNum)
{
hoursWorked = _hours;
hourlyWage = _wage;
}
public double HoursWorked
{
get { return hoursWorked; }
set { hoursWorked = value; }
}
public double HourlyWage
{
get { return hourlyWage; }
set { hourlyWage = value; }
}
// calculates gross pay
// hours * wage + time and 1/2 for overtime
public override double CalcPay()
{
double overTime = 0.0;
if (hoursWorked > WEEK)
{
overTime = hoursWorked - WEEK;
hoursWorked -= WEEK;
}
double grossPay = hoursWorked * hourlyWage + overTime * hourlyWage * BONUS;
double stateTax = grossPay * STATE_TAX;
double fedTax = grossPay * FED_TAX;
return (grossPay - stateTax - fedTax);
}
// reads object's data from a StreamReader object
// Over-rides the ReadData method in Employee
public override void ReadData(StreamReader sro)
{
HoursWorked = double.Parse(sro.ReadLine());
HourlyWage = double.Parse(sro.ReadLine());
base.ReadData(sro);
}
// writes object's data to a StreamWriter object
// Over-rides the WriteData method in Employee
public override void WriteData(StreamWriter swo)
{
swo.WriteLine("hourly");
swo.WriteLine(this.HoursWorked);
swo.WriteLine(this.HourlyWage);
base.WriteData(swo);
}
}
class Salaried : Employee
{
private const double BENEFITS = 0.0524;
private double salary;
// set data members to defaults
public Salaried()
{
salary = 0.0;
}
// set data members to values passed as arguments
// employee number, name, address, phone number, salary
public Salaried(int _empNum, string _name, string _address, string _phoneNum, double _salary)
: base(_empNum, _name, _address, _phoneNum)
{
salary = _salary;
}
public double Salary
{
get { return salary; }
set { salary = value; }
}
// calculates pay for a salaried employee
public override double CalcPay()
{
double stateTax = salary * STATE_TAX;
double fedTax = salary * FED_TAX;
double bennies = salary * BENEFITS;
return (salary - stateTax - fedTax - bennies);
}
//reads object's data from a StreamReader object
public override void ReadData(StreamReader sro)
{
Salary = double.Parse(sro.ReadLine());
base.ReadData(sro); // call Employee's ReadData to get name, address, etc
}
// writes data to StreamWriter
public override void WriteData(StreamWriter swo)
{
swo.WriteLine("salaried");
swo.WriteLine(this.Salary);
base.WriteData(swo);
}
}
}
Thanks in advance for any help.
Use listbox's click event; Cast the SelectedItems[0] as employee and populate the textboxes. Set multiple selection of the listbox to false for simplicity. eg:
private void listBox1_Clik(object sender, EventArgs e)
{
Employee employee = listBox1.SelectedItems[0] as Employee;
if (employee != null)
{
// use the employee object to populate the textbox.
}
}
Take a look at the SelectedIndexChanged event on ListBox, it might do what you want. In fact the sample code in the docuemntation shows how to select an item in a second ListBox when an item is selected in the first ListBox so that should give you some idea.

Categories