Edit: Changed System.Array.Clear(new[] {1,2,3}, 0, 2); to System.Array.Clear(numbers, 0, 2); but get the output [0, z0, z3] and was expecting [0,0,3]
I'm learning about C# and currently learning about arrays and Clear(). When trying to see what happens when using Clear(), I get this output:
I don't understand why this happens. Wasn't it supposed to be [0,0,3]?
My code looks like this:
Program.cs
namespace Introduction
{
internal class Program
{
/* MAIN FUNCTION */
public static void Main()
{
// RunControlFlow();
RunArrays();
}
/* ARRAYS */
public static void RunArrays()
{
// Var declaration
var array = new Arrays.Array();
array.Manipulation();
}
}
}
Arrays.cs
using System;
namespace Introduction.Arrays
{
public class Array
{
public void Manipulation()
{
var numbers = new[] {1, 2, 3};
System.Array.Clear(numbers, 0, 2);
Console.WriteLine("Manipulation | Clearing from index 0 to 2: [{0}]", string.Join(",z", numbers));
}
}
}
You are not passing the numbers array to the Clear method, you are creating a new array that has the same elements, but it's a completely different reference and has nothing to do with numbers. That is why the values in numbers stays unchanged:
Array.Clear(numbers, 0, 2);
Related
I am trying to make a small console application for an ATM machine, and I am struggling with the Insert method of this Program, so it goes like this:
public void Insert(int[] cash) //I cannot change the type or parameter of the method
{
for (int i = 0; i < cash.Length; i++) // using .Length input into the array
{
cash[i] = Convert.ToInt32(Console.In.ReadLine());
}
bool IsntAcceptable = cash.Intersect(AcceptableBanknotes).Any(); // Acepttable Banknotes variable is a array like this private int []AcceptableBanknotes = { 5, 10, 20, 50, 100 };
if (IsntAcceptable)
{
throw new ArgumentException("Only acceptable banknotes are 5, 10, 20, 50 and 100");
}
this.Balance += cash.Sum(); // add to balance
Console.Write(this.Balance);
}
In my main it looks like this
static void Main(string[] args)
{
// some other code here
Console.WriteLine("\nEnter the amount to deposit: ");
atm.Balance = atm.Insert(Array.ConvertAll(Console.ReadLine().Trim().Split(' '), Convert.ToInt32));
}
but it just gives me an error of Error CS0029 Cannot implicitly convert type 'void' to 'int'
I would be very grateful for any help or guidance you could give me, thanks in advance!
You are not returning anything from Insert that is the cause an issue. Just change it to normal call and it will work for you like below:
atm.Insert(Array.ConvertAll(Console.ReadLine().Trim().Split(' '), Convert.ToInt32));
or if you want to return something from that method then make that method with specific type as per your requirements.
Looks like you're trying to make Insert an extension method to atm. If that's the case your Insert method needs to be static and take atm as a parameter. If you're going down the route of extension methods I'd create a separate class for your extensions like this:
public static class AtmExtensions
{
public static void Insert(this Atm atm, int[] cash)
{
// your logic.
}
}
Where Atm is a separate class composing of the various properties like Balance.
Next thing is that your passing in the values read from the console only to ignore that later and read from the console again. Read the values from the console and then use that where needed. So in this case you can remove the for loop as you've already converted the values to ints.
Finally, you're expecting Insert to set atm.Balance in the Main method, but it's void so doesn't return anything, and is setting it anyway as part of the Insert method. So, I think what you're trying to achieve should look something like this:
Your Atm class:
public class Atm
{
public int Id { get; set; }
public decimal Balance { get; set; }
// other properties...
}
A new class for holding all your extension methods for Atm:
public static class AtmExtensions
{
public static void Insert(this Atm atm, int[] cash)
{
var acceptableBanknotes = new int[] { 5, 10, 20, 50, 100 };
if (cash.All(note => acceptableBanknotes.Contains(note)))
{
atm.Balance += cash.Sum();
Console.Write(atm.Balance);
}
else
{
throw new ArgumentException("Only acceptable banknotes are 5, 10, 20, 50 and 100");
}
}
}
Called like this:
static void Main(string[] args)
{
var atm = new Atm();
Console.WriteLine("\nEnter the amount to deposit: ");
atm.Insert(Array.ConvertAll(Console.ReadLine().Trim().Split(' '), Convert.ToInt32));
}
This is an error caused by putting an void type in the member variable atm.balance.
public int Insert(int[] cash) //I cannot change the type or parameter of the method
{
for (int i = 0; i < cash.Length; i++) // using .Length input into the array
{
cash[i] = Convert.ToInt32(Console.In.ReadLine());
}
bool IsntAcceptable = cash.Intersect(AcceptableBanknotes).Any(); // Acepttable Banknotes variable is a array like this private int []AcceptableBanknotes = { 5, 10, 20, 50, 100 };
if (IsntAcceptable)
{
throw new ArgumentException("Only acceptable banknotes are 5, 10, 20, 50 and 100");
}
this.Balance += cash.Sum(); // add to balance
//If you return Balance, you don't need this sentence.
Console.Write(this.Balance);
return Balance;
}
OR
static void Main(string[] args)
{
// some other code here
Console.WriteLine("\nEnter the amount to deposit: ");
atm.Insert(Array.ConvertAll(Console.ReadLine().Trim().Split(' '), Convert.ToInt32));**
}
I want to write a card exchange game. I have an Arraylist of Colors in which values start from -1 to 6. Each element of this array implies id colors. There is also an ArrayList Player Properties in which cards with colors are stored. I need to create an ArrayList with eight zeros that will imply id Colors. Next, skip the ArrayList Player Properties through this array and if there is some element in the array, then increase the ArrayList Colors index by +1.
Eg:
ArrayList Colors =new ArrayList(){-1,0,1,2,3,4,5,6};
ArrayList Player Properties = new ArrayList(){0,4,6};
This array should imply that its element is an element of the Colors array
ArrayList buffer = new ArrayList(){0,0,0,0,0,0,0,0};
If an array comes to the input in this form: {0,4,6};
Then the index of this array is added by +1, like this: {0,1,0,0,0,1,0,1};
How do I implement this in code?
I don't have any code examples because I don't know how to implement it, sorry in advance that I didn't provide more code, I really need help, thank you all in advance for your help
You can use the Linq function Contains to check if a value is present in an array. Something like this:
var colors = new int[] { -1, 0, 1, 2, 3, 4, 5, 6 };
var playerProperties = new int[] { 0, 4, 4, 6 };
var result = colors.Select(c => playerProperties.Where(x => x == c).Count());
Console.WriteLine(string.Join(", ", result));
prints 0, 1, 0, 0, 0, 2, 0, 1
What you want is a histogram of the card values that you accumulate.
Since this is C# you better start thinking of a data model for each player. There are two arrays to consider, one with the card values: -1,0,..6 and one with the card counts, how many of each card a player has.
Here is how this would play out:
static class Program
{
static void Main(string[] args)
{
var player1 = new Player("Player1");
Console.WriteLine(player1);
// Player1 : 0,0,0,0,0,0,0,0
player1.Hand(0,4,6);
Console.WriteLine(player1);
// Player1: 0,1,0,0,0,1,0,1
}
}
You can to this point with the following Player class that handles the logic inside the .Hand() method.
public class Player
{
public static readonly int[] CardValues = { -1, 0, 1, 2, 3, 4, 5, 6 };
public Player(string name)
{
CardCounts = new int[CardValues.Length];
Name = name;
}
public int[] CardCounts { get; }
public string Name { get; }
public void Hand(params int[] cards)
{
foreach (var card in cards)
{
int index = Array.IndexOf(CardValues, card);
if (index >= 0)
{
CardCounts[index] += 1;
}
}
}
public override string ToString()
{
return $"{Name} : {string.Join(",", CardCounts)}";
}
}
Note that ArrayList is really old technology, and not type safe. In it place there is List<>, but in this case the length of the array is fixed since there is a finite set of card values, and that does not change, so no need for a collection, as a plain old Array would suffice.
Because your array is a fixed representation:
var Colors = new []{-1,0,1,2,3,4,5,6};
var PlayerProperties = new []{0,4,6};
var buffer = new []{0,0,0,0,0,0,0,0};
You can calculate which indexes in the buffer should be set to 1
foreach(var pp in PlayerProperties)
buffer[pp+1] += 1;
Value 0 always occurs at index 1. Value 4 always occurs at index 5. Value 6 always occurs at index 7. Thus the formula is value+1..
The task is to write a simple method that can sort int array (in ascending or descending order - should be set as enum type parameter of this method). I have written the method itself and enum, but I have no idea how to set enum as method parameter:(
Would be great to get any help from you, guys, cause I am completely new to coding.
class Program
{
public enum options
{
UpSortOption,
DownSortOption
}
public static void Main(string[] args)
{
int[] arr = new int[] { 3, 8, 0, 2, 16 };
}
static void orderArray(int [] array, options op)
{
switch(op)
{
case options.UpSortOption:
Array.Sort(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
break;
case options.DownSortOption:
Array.Sort(array);
Array.Reverse(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
break;
}
}
}
The signature of the method looks fine, Now you wanted to call this method by passing the first parameter of type integer array and the second parameter of type options for that you can use the following code:
orderArray(arr,options.UpSortOption);
Or else you can declare a variable of type options and pass that variable, the change you have to make for that case will be:
options optionsVariable = options.DownSortOption;
orderArray(arr,optionsVariable);
Let's take a step back to see if it helps your understanding.
If you have a method that takes a string and an int like this
string MyMethod(string str, int num)
{
// Do something
}
You'd use it like this
string rslt = MyMethod("Hello", 123);
What you've got here is something that takes in some stuff, does something to it, and gives you something in return. In this case MyMethod takes a string and an int, does something with them and returns a string which you then call rslt.
Your example follows the same basic pattern so you need to take your method - orderArray and give it the two things it wants - an int array and an option like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
orderArray(arr, options.UpSortOption);
Alternatively, you could create an options much like you'd create a string and then call your method like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
options myOption = options.UpSortOption;
orderArray(arr, myOption);
To fully illustrate the point that an enum as a parameter isn't any different from say a string you could modify your method like this
static void orderArray(int[] array, string op)
{
if (op == "UpSortOption")
{
Array.Sort(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
}
else
{
Array.Sort(array);
Array.Reverse(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
}
}
Then call it like this
int[] arr = new int[] { 3, 8, 0, 2, 16 };
string myOption = "UpSortOption";
orderArray(arr, myOption);
This is how you pass it as a parameter
orderArray(int [] array, typeof(options)){
//Beep bap boop
}
Hope this aids you.
Exactly that's how you set up Enum as a method parameter.
To call this method use:
orderArray(arr, options.UpSortOption);
You can also assign enum value to a variable and use this to call a method:
options sortOpt = options.UpSortOption;
orderArray(arr, sortOpt);
You can also cast integer to an enum:
orderArray(arr, (options)0);
OR
int opt = 0;
orderArray(arr, (options)opt);
Remembering, that if not specified otherwise, first element is 0, second is 1 and so on.
By the way, you should rather use PascalCase to name an enum type, like:
public enum Options
{ ... }
I was trying to translate this python code for a Neural Network
https://gist.github.com/miloharper/c5db6590f26d99ab2670#file-main-py
in C#. I'm using the Math.Net Numerics for the matrixes and here is the code I've made so far in C#
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra.Double;
namespace NeuralNetwork
{
class Program
{
static void Main(string[] args)
{
NeuralNetwork NN = new NeuralNetwork();
Console.WriteLine("Random starting synaptic weights: ");
Console.WriteLine(NN.SynapticWeights);
Matrix<double> TrainingSetInput = DenseMatrix.OfArray(new double[,] { { 0, 0, 1 }, { 1, 1, 1 }, { 1, 0, 1 }, { 0, 1, 1 } });
Matrix<double> TrainingSetOutput = DenseMatrix.OfArray(new double[,] { { 0, 1, 1, 0 } }).Transpose();
NN.Train(TrainingSetInput, TrainingSetOutput, 10000);
Console.WriteLine("New synaptic weights after training: ");
Console.WriteLine(NN.SynapticWeights);
Console.WriteLine("Considering new situation {1, 0, 0} -> ?: ");
Console.WriteLine(NN.Think(DenseMatrix.OfArray(new double[,] { { 1, 0, 0 } })));
Console.ReadLine();
}
}
class NeuralNetwork
{
private Matrix<double> _SynapticWeights;
public NeuralNetwork()
{
_SynapticWeights = 2 * Matrix<double>.Build.Random(3, 1) - 1;
}
private Matrix<double> Sigmoid(Matrix<double> Input)
{
return 1 / (1 + Matrix<double>.Exp(-Input));
}
private Matrix<double> SigmoidDerivative(Matrix<double> Input)
{
return Input * (1 - Input); //NEW Exception here
}
public Matrix<double> Think(Matrix<double> Input)
{
return Sigmoid((Input * _SynapticWeights)); //Exception here (Solved)
}
public void Train(Matrix<double> TrainingInput, Matrix<double> TrainingOutput, int TrainingIterations)
{
for (int Index = 0; Index < TrainingIterations; Index++)
{
Matrix<double> Output = Think(TrainingInput);
Matrix<double> Error = TrainingOutput - Output;
Matrix<double> Adjustment = Matrix<double>.op_DotMultiply(TrainingInput.Transpose(), Error * SigmoidDerivative(Output));
_SynapticWeights += Adjustment;
}
}
public Matrix<double> SynapticWeights { get { return _SynapticWeights; } set { _SynapticWeights = value; } }
}
}
When I execute it, it shows an exception on line 53 (there is a comment at that line in the code). It says:
Matrix dimensions must agree: op1 is 4x3, op2 is 3x1
Did I copy it wrong or is it a problem with the MAth.Net library?
Thanks in advance :D
As far as I can see, the problem not in the library code. You are trying to perform an element-wise matrix multiplication with the use of op_DotMultiply function (line 53). In this case it is obvious from the error message that matrices cannot be multiplied due to difference in their size: the first one is 4x3, the second one is 3x1.
I can suggest to look at the size of these matrices: TrainingSetInput and _SynapticWeights (look at function Train, you are calling Think inside of it with the wrong sized matrices). Check if they are generated correctly. And also think if you really need an element-wise matrix multiplication or a usual multiplication.
If you need more info about matrix multiplications, you can use these links:
Element-wise:
https://en.wikipedia.org/wiki/Hadamard_product_(matrices)
Usual:
https://en.wikipedia.org/wiki/Matrix_multiplication
Im creating an two dimensional array and giving the user the chance to set there double variables. When i want to print out the result, it is shown without points
exp: user entry 3.45 -> 345
Conver.ToDouble doesnt function neither
the following code shows my "programm" nevermind exception handling
static void Main(string[] args)
{
double[,] Array = new double[,] { { 0, 0, 0}, { 0, 0, 0 }, { 0, 0, 0 } };
array Object = new array();
array[0,0] = Double.Parse(Console.ReadLine());
Console.WriteLine("Wert = {0}",intArray[0,0]);
Console.ReadKey();
}
}
Multiply the values by 100, and then use the following format string:
Console.WriteLine("Wert = {0:F0}",intArray[0,0] * 100);
Your code has a lot of errors as I found:
corrected code is:
static void Main(string[] args)
{
double[,] Array = new double[,] { { 0, 0, 0}, { 0, 0, 0 }, { 0, 0, 0 } };
//array Object = new array(); //no need of this because you are not using it any where
Array[0,0] = Double.Parse(Console.ReadLine()); //"array" doesn't exist, it should be "Array"
Console.WriteLine("Wert = {0}",Array[0,0]); //"intArray" has not been initialized, it should be "Array" in you case
Console.ReadKey();
}
Here is the output:
I hope it will work now.