Title: Find two sets where the median of one is the mean of the other and vice versa in C#
For an upcoming book, I wanted to find sets where the mean (average) of one is the median (middle value) of the other and vice versa. I wanted to avoid trivial examples such as {1, 1, 1} and where the two sets are the same.
This example does that by making a list of all possible sets containing three values between one and a maximum that you specify. It then compares two lists of sets and compares means and medians.
The following method generates the sets.
private List<List<int>> Triples(int max)
{
List<List<int>> results = new List<List<int>>();
for (int i = 1; i < max; i++)
for (int j = i + 1; j < max; j++)
for (int k = j + 1; k < max; k++)
{
results.Add(new List<int>(new int[] { i, j, k }));
}
return results;
}
This method simply uses three loops to generate sets containing three items. Each looping variable starts one greater than the previous one. For example, j starts looping at i + 1. That prevents the sets from having duplicate values. It also means the values in a set are sorted so the median value is the second one in the set.
The following code shows how the program uses the list of sets.
private void btnGo_Click(object sender, EventArgs e)
{
lstMatches.Items.Clear();
lblNumMatches.Text = "";
Cursor = Cursors.WaitCursor;
Refresh();
int max = int.Parse(txtMax.Text);
List<List<int>> list1 = Triples(max);
foreach (List<int> triple1 in list1)
{
int sum1 = triple1.Sum();
if (sum1 % 3 != 0) continue;
int mean1 = sum1 / 3;
int median1 = triple1[1];
if (mean1 == median1) continue;
foreach (List<int> triple2 in list1)
{
if ((triple1[0] == triple2[0]) &&
(triple1[1] == triple2[1]) &&
(triple1[2] == triple2[2]))
continue;
int sum2 = triple2.Sum();
if (sum2 % 3 != 0) continue;
int mean2 = sum2 / 3;
int median2 = triple2[1];
if (mean2 == median2) continue;
if ((mean1 == median2) && (mean2 == median1))
{
// Find sets where the mean of one is the
// median of the other and vice versa.
lstMatches.Items.Add(
TripleString(triple1) + '\t' +
TripleString(triple2));
Console.WriteLine(
TripleString(triple1) + '\t' +
triple1.Sum() / 3 + '\t' +
triple1[1].ToString() + '\t' +
TripleString(triple2) + '\t' +
triple2.Sum() / 3 + '\t' +
triple2[1].ToString());
Refresh();
}
}
}
lblNumMatches.Text = lstMatches.Items.Count.ToString();
Cursor = Cursors.Default;
}
This code makes a list containing the possible sets. It then makes variable triple1 loop through the list. For each set, it calculates the set's mean and median. It then makes variable triple2 loop over the sets, again.
If the two sets are the same, the loop continues. If the sets are different, the code calculates the second set's mean and median and compares the values for the two sets. If there's a match, the program adds the two sets to the lstMatches list box. It also adds the sets, their means, and their medians to the Console window.
Download the example to experiment with it and to see additional details.
|