1-9九个数字不重复组成一个三位数加法算式,求出所有组合

时间:2022-11-05 15:35:28

此题咱没想出很巧妙的解法,直接根据编程来吧

方法一:

using System;
using System.Collections.Generic;
using System.Text;

namespace RemainerMaths
{
class Program
{
static void Main(string[] args)
{
int count = 0;//可能性个数
int[] a ={ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < a.Length; j++)
{
for (int k = 0; k < a.Length; k++)
{
if (a[i] != a[j] && a[j] != a[k] && a[k] != a[i])
{
//从9个数中随机找出3个数组成三位数
int add1 = 100 * a[i] + 10 * a[j] + a[k];

//将剩下的6个数字组成一个数组
int[] b = GetNewArray(a, i, j, k);
for (int x = 0; x < b.Length; x++)
{
for (int y = 0; y < b.Length; y++)
{
for (int z = 0; z < b.Length; z++)
{
if (b[x] != b[y] && b[y] != b[z] && b[z] != b[x])
{
//从这6个数中随机找出3个数组成三位数
int add2 = 100 * b[x] + 10 * b[y] + b[z];
//将剩下的3个数字组成一个数组
int[] c = GetNewArray(b, x, y, z);
//获得最后剩下的3个数字组成的所有三位数
int[] lastNumber = GetAllThreeNumber(c);
//如果两数之和等于第三个数就输出
for (int index = 0; index < lastNumber.Length; index++)
{
if (add1 + add2 == lastNumber[index])
{
count++;
Console.WriteLine("{0} + {1} = {2}", add1, add2, lastNumber[index]);
break;
}
}
}
}
}
}
}
}
}
}
Console.WriteLine("共有[{0}]种情形-因加法存在交换律,则实际有[{1}]种情形。", count, count/2);
Console.ReadLine();
}

/// <summary>
/// 由原数组,去除掉索引在i、j、k处的元素后形成的新数组
/// </summary>
/// <param name="a"></param>
/// <param name="i"></param>
/// <param name="j"></param>
/// <param name="k"></param>
/// <returns></returns>
static int[] GetNewArray(int[] a, int i, int j, int k)
{
List<int> list = new List<int>();
for (int temp = 0; temp < a.Length; temp++)
{
if (temp != i && temp != j && temp != k)
{
list.Add(a[temp]);
}
}
int[] b = list.ToArray();
return b;
}

/// <summary>
/// 获得由最后三个数字组成的所有三位数
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
static int[] GetAllThreeNumber(int[] list)
{
List<int> temp = new List<int>();
if (list == null || list.Length != 3)
return temp.ToArray();
temp.Add(100 * list[0] + 10 * list[1] + list[2]);
temp.Add(100 * list[0] + 10 * list[2] + list[1]);
temp.Add(100 * list[1] + 10 * list[0] + list[2]);
temp.Add(100 * list[1] + 10 * list[2] + list[0]);
temp.Add(100 * list[2] + 10 * list[0] + list[1]);
temp.Add(100 * list[2] + 10 * list[1] + list[0]);
return temp.ToArray();
}
}
}

输出结果:

1-9九个数字不重复组成一个三位数加法算式,求出所有组合

。。。。。。

1-9九个数字不重复组成一个三位数加法算式,求出所有组合