I'm reading a C# book for beginners, and in every end of the chapter, there are exercises to be answered based on the lessons tackled.
One of those exercises goes this way: (not the exact wordings)
Write a program that will accept an int as the array length, and the values for the array.
Then will print:
"0" if the array is not sorted in ascending way.
"1" if it is sorted. And,
"2" if it is sorted, but there are duplicates.
Example:
// Sorted
Input: 1, 2, 3, 5
Print: 1
// Not sorted
Input: 2, 1, 3, 6
Print: 0
// Sorted, but with duplicates
Input: 2, 2, 3, 7
Print: 2
I don't know if my logic here is absolute, but somehow it is working,
and I done it in my way using this code:
int arrayLength = 0;
int prev, next;
int sortStatus = 1;
Console.Write("Input array Length: ");
arrayLength = Convert.ToInt32(Console.ReadLine());
int[] ar = new int[arrayLength];
for (int x = 0; x < arrayLength; x++)
{
Console.Write("Input {0} value: ", (x+1).ToString());
ar[x] = Convert.ToInt32(Console.ReadLine());
}
for (int x = 0; x < ar.Length-1; x++)
{
prev = (int)ar[x];
next = (int)ar[x + 1];
if (next < prev)
sortStatus = 0;
if (next == prev)
sortStatus = 2;
}
Console.Write(sortStatus.ToString());
Console.Read();
Is it possible to express this in LINQ? How?
Define an Expression Linq. Expressions namespace and use an Expression<TDelegate> class to define an Expression. Expression<TDelegate> requires delegate type Func or Action. in the same way, you can also wrap an Action<t> type delegate with Expression if you don't return a value from the delegate.
Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language. Traditionally, queries against data are expressed as simple strings without type checking at compile time or IntelliSense support.
An expression in C# is a combination of operands (variables, literals, method calls) and operators that can be evaluated to a single value. To be precise, an expression must have at least one operand but may not have any operator.
The Select() method invokes the provided selector delegate on each element of the source IEnumerable<T> sequence, and returns a new result IEnumerable<U> sequence containing the output of each invocation.
if (ar.SequenceEqual(ar.OrderBy(x => x)))
{
if (ar.Distinct().Count() == ar.Length)
return 1;
else
return 2;
}
else
{
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With