I’m trying to learn C#, so I’m doing assignments on open.kattis.com.
I have three variables called A, B and C and have to print them in a given order.
A is the smallest variable, B is the middle variable and C is the largest variable.
I give the variables 1, 2, 5 and the order ABC, so the output print is 1 2 5
I give the variables 1, 10, 22 and the order CAB, so the output is 22 1 10
My question however is to improve my code. Right now I’m checking the input-order in a switch-case and was wondering if there is a better way.
My submission can be seen here:
using System;
using System.Linq;
class Program
{
public static void Main(string[] args)
{
string[] input = Console.ReadLine().Split(' ');
string order = Console.ReadLine();
int[] inputArray = {0, 0, 0};
int A = 0, B = 0, C = 0;
for (int i = 0; i < input.Length; i++)
{
inputArray[i] = Int32.Parse(input[i]);
}
A = inputArray.Min();
C = inputArray.Max();
for (int i = 0; i < inputArray.Length; i++)
{
if (inputArray[i] != A && inputArray[i] != C)
{
B = inputArray[i];
}
}
switch (order)
{
case "ABC":
Console.WriteLine($"{A} {B} {C}");
break;
case "ACB":
Console.WriteLine($"{A} {C} {B}");
break;
case "BAC":
Console.WriteLine($"{B} {A} {C}");
break;
case "BCA":
Console.WriteLine($"{B} {C} {A}");
break;
case "CBA":
Console.WriteLine($"{C} {B} {A}");
break;
case "CAB":
Console.WriteLine($"{C} {A} {B}");
break;
}
}
}
>Solution :
Let’s generalize the solution. So you have data array:
int[] inputArray = new int[] {1, 2, 3}
and order:
string order = "BAC";
Now we can loop over order and output corresponding array’s item:
for (char letter in order)
Console.Write($"{inputArray[letter - 'A']} ");
Here we convert letters from order (B, A, C) into indexes (1, 0, 2)
Please note, that we can well use array, say, of 2 or 4 items providing that we have corresponding order
Code:
public static void Main(string[] args) {
// We don't have to parse, just to split
string[] inputArray = Console
.ReadLine()
.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
string order = Console.ReadLine();
for (char letter in order)
Console.Write($"{inputArray[letter - 'A']} ");
}