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
{ ... }
Related
I'm trying to write code that makes a union between array a and b (AUB), but when I want to print the combined array. the console prints System.Int32\[\].
For context, if my
array a = { 1, 3, 5, 6 }
and my
array b = { 2, 3, 4, 5 }
my union array should be
combi = { 1, 2, 3, 4, 5, 6 }
but like I said, combi prints out as System.Int32\[\]
I don't know if it's the way I'm doing the union or if its the way I'm printing it. I'm also trying to do a
A intersection B and A – B
But I haven't tried anything of those yet, I would appreciate if you have any tips.
using System;
using System.Reflection.Metadata.Ecma335;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("size of A? ");
int a = Convert.ToInt32(Console.In.ReadLine());
Console.WriteLine("Value of A:");
int[] ans = new int[a];
for (int i = 0; i < ans.Length; i++)
{
ans[i] = Convert.ToInt32(Console.In.ReadLine());
}
Console.WriteLine("size of B?");
int b = Convert.ToInt32(Console.In.ReadLine());
Console.WriteLine("Value of B:");
int[] anse = new int[b];
for (int i = 0; i < anse.Length; i++)
{
anse[i] = Convert.ToInt32(Console.In.ReadLine());
}
var combi = new int[ans.Length + anse.Length];
for (int i = 0; i < combi.Length; i++)
{
Console.WriteLine(combi + " ");
}
Console.ReadLine();
}
}
}
when i want to print the combined array the console prints
System.Int32[]
If you write Console.Write(someObject), the method tries to find an overridden ToString in someObject. If there is none System.Object.ToString is used which just returns the fully qualified name of the type of the Object, which is "System.Int32[]" in case of an int[].
If you want to print out an array of integers one approach would be to use string.Join:
string spaceSeparatedList = string.Join(" ", combi);
Now you have a space-separated list of integers.
In the code You have just initialized the size of the array of Combi Array not assign the values
First you have to add Array a and Array b values into combi array
Then try to print into union,see below code for the reference:
List<int> combi = new List<int>();
foreach(var first in ans)
{
combi.Add(first);
}
foreach (var second in anse)
{
combi.Add(second);
}
combi.Sort();
string result = string.Join(",",combi);
Console.WriteLine(result);
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 am strugling with the int[Array] since yesterday.
I have the following code:
public int[] Numbers
{
get
{
return class.intNumbers();
}
set
{
int[] Number = class.intNumbers();
Number[Number.Length + 1] = value;
writer.NumberValue("Name", "Id", "Here goes the Array");
}
}
What I want the code to do is to take the array from other class and on the next index to put my value.(Fails at Number[Number + 1] = value;) The get method is succesfully finished, all I have to do now is "set". Do you have any ideas?
P.S I only want to use array and not arraylist :)
You can use ArrayResizer, although I don't know why you do not want to use List here.
int[] arr = { 1, 2, 3 };
Array.Resize(ref arr , 5);
https://msdn.microsoft.com/en-us/library/bb348051(v=vs.110).aspx
You could also implement private List<int> numberList
Then return numberList.ToArray(); in getter.
I have this function that call itself to find all the possible combination with the array of int. The problem is that the program calculate the first combination and then, when the recursion continues, the List of combination still contains that value and i don't understand why.
public static void Permutation(List<int> items, int h, List<int> actualCombination)
{
if (h == actualCombination.Count)
{
results[results.Count] = actualCombination;
}
else
{
for (int i = 0; i < items.Count; i++)
{
actualCombination.Add(items[i]);
List<int> temp = new List<int>(items);
temp.Remove(items[i]);
Permutation(temp, h, actualCombination);
}
return;
}
}
after that, i call the function in main. In my case the second parameter specify the combination length."Results" is a Dictionary composed by int as key and List as value that is used to save all the combination.
static void Main(string[] args)
{
Permutation(new List<int> { 1, 2, 3 }, 3, new List<int>());
Console.ReadKey();
}
I solved the problem by copying the List before of the function add.
I have a function GetPivotedDataTable(data, "date", "id", "flag") is returning data in Pivoted format. I want to call this method using Task but how to pass multiple parameter in Task.
You could use lambda expression, or a Func to pass parameters:)
public Form1()
{
InitializeComponent();
Task task = new Task(() => this.GetPivotedDataTable("x",DateTime.UtcNow,1,"test"));
task.Start();
}
public void GetPivotedDataTable(string data, DateTime date, int id, string flag)
{
// Do stuff
}
In case that your parameters are of diferent types you could use an array of object and then typecast back to the original types.
Check out this console application example:
static void Main(string[] args)
{
var param1String = "Life universe and everything";
var param2Int = 42;
var task = new Task((stateObj) =>
{
var paramsArr = (object[])stateObj; // typecast back to array of object
var myParam1String = (string)paramsArr[0]; // typecast back to string
var myParam2Int = (int)paramsArr[1]; // typecast back to int
Console.WriteLine("");
Console.WriteLine(string.Format("{0}={1}", myParam1String, myParam2Int));
},
new object[] { param1String, param2Int } // package all params in an array of object
);
Console.WriteLine("Before Starting Task");
task.Start();
Console.WriteLine("After Starting Task");
Console.ReadKey();
}
You could create a helper class that will hold all parameters that you need in your task.
You can use "params" also. check c# params info
public class MyClass
{
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.Write(list[i] + " ");
}
Console.WriteLine();
}
static void Main()
{
// You can send a comma-separated list of arguments of the
// specified type.
UseParams(1, 2, 3, 4);
UseParams2(1, 'a', "test");
// A params parameter accepts zero or more arguments.
// The following calling statement displays only a blank line.
UseParams2();
// An array argument can be passed, as long as the array
// type matches the parameter type of the method being called.
int[] myIntArray = { 5, 6, 7, 8, 9 };
UseParams(myIntArray);
object[] myObjArray = { 2, 'b', "test", "again" };
UseParams2(myObjArray);
// The following call causes a compiler error because the object
// array cannot be converted into an integer array.
//UseParams(myObjArray);
// The following call does not cause an error, but the entire
// integer array becomes the first element of the params array.
UseParams2(myIntArray);
}
}
/*
Output:
1 2 3 4
1 a test
5 6 7 8 9
2 b test again
System.Int32[]
*/
You can use Tuple
Task<Tuple<Tuple<Parame1,Parame2,Parame....>> Func()
{
}
var r = await Func();
r.Item1;
r.Item2;
r.Item.....