c# - How do i arrange 3 numbers from biggest to smallest without using 5 if's -
i receive 3 numbers , i'm supposed display them biggest smallest, know how 5 if statements i'm pretty sure there's more efficient way this, don't know is.
int = int.parse(console.readline()); int b = int.parse(console.readline()); int c = int.parse(console.readline()); if (a > b) { if (a > c) { console.writeline("{0},{1},{2}", a, b, c); } else { console.writeline("{0},{1},{2}",c,a,b); } }
it's quite simple. store numbers in array , sort array:
var arr = new[] { a, b, c }; array.sort(arr); array.reverse(arr); console.writeline("{0}, {1}, {2}", arr[0], arr[1], arr[2]);
you can use following (which quite bit faster, harder understand if you're beginner):
var arr = new[] { a, b, c }; array.sort(arr, new comparison<int>((x, y) => y.compareto(x))); console.writeline("{0}, {1}, {2}", arr[0], arr[1], arr[2]);
in case, skip call array.reverse
because you're passing in custom comparison
delegate specifies comparison should reversed.
Comments
Post a Comment