Problem 1-7

CSharp · Console

/Program.cs

// The bus lines M1 and M2 both go along the Moscow Prospect.
// Find how many common stops they have. 
// All stops are numbered sequentially along the prospect;
// the bus never skips a stop on its path. 
// The program should input 4 numbers (the first and last stop of each bus)
// and output the number of common stops.

using System;
					
public class Program
{
	public static int InputInt(string prompt)
	{
		Console.Write("Enter " + prompt + ":");
		return Convert.ToInt32(Console.ReadLine());
	}

	public static int Max(int x, int y)
	{
		if(x > y) return x; else return y;
	}

	public static int Min(int x, int y)
	{
		if(x < y) return x; else return y;
	}

	public static void Main(string[] args)
	{
		int m1a = InputInt("M1 first stop");
		int m1b = InputInt("M1 last stop");
		int m2a = InputInt("M2 first stop");
		int m2b = InputInt("M2 last stop");

		// normalize input
		int m1min = Min(m1a, m1b);
		int m1max = Max(m1a, m1b);
		
		int m2min = Min(m2a, m2b);
		int m2max = Max(m2a, m2b);
		
		// mNmin <= mNmax for N=1,2
		
		int bothMin = Max(m1min, m2min); // smallest possible common stop
		int bothMax = Min(m1max, m2max); // biggest possible common stop
		
		int nCommon;
		if(bothMin <= bothMax)
			nCommon = bothMax - bothMin + 1;
		else
			nCommon = 0;
		
		Console.WriteLine(nCommon.ToString());
	}
}

;