如何提取出某个数组里的所有等差元素?[
随机给定一个有N个元素的数组。规定的条件是:形成等差的元素必须大于三个。
比如数组是{1,5,3,6,4,2}
那么符合条件的有:
{1,2,3,4,5,6}
{1,3,5}
{2,4,6}
以下几个因为元素小于3个,所以不符合:
{1,2}
{1,3}
……
还请高手指点一下。谢谢!
[解决办法]
给你写个程序(没有做任何优化考虑):
using System;using System.Collections.Generic;using System.Linq;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var Array = new List<int> { 1, 5, 3, 6, 4, 2 }; var MaxDiv = 3; //所谓“等差”这个差的上限值 var query = from x in Array from d in Enumerable.Range(1, MaxDiv) let result = 等差元素(Array, x, d) where result.Count() >= 3 select result; foreach (var r in query) { r.ToList().ForEach(x => { Console.Write("{0} ", x); }); Console.WriteLine(); } Console.ReadKey(); } static IEnumerable<int> 等差元素(List<int> array, int from, int div) { if (array.Contains(from)) { yield return from; foreach (var x in 等差元素(array, from + div, div)) yield return x; } } }}
[解决办法]
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { int[] source = { 1, 5, 3, 6, 4, 2 }; int[] data = source.OrderBy(x => x).ToArray(); List<List<int>> result = new List<List<int>>(); for (int i = 0; i < data.Length; i++) { var temp = result.Where(x => x.Count == 1 || (x.Count > 1 && x[1] - x[0] == data[i] - x.Last())).ToList(); if (temp.Count > 0) { result = result.Concat(result.Where(x => x.Count == 1).Select(x => x.ToList())).ToList(); temp.ForEach(x => x.Add(data[i])); } result.Add(new List<int> { data[i] }); } result = result.Where(x => x.Count > 2).ToList(); foreach (var item in result.ToList()) { if (result.Any(x => x.Count > item.Count && item.Except(x).Count() == 0 && x[1] - x[0] == item[1] - item[0])) result.Remove(item); } foreach (var item in result) { Console.WriteLine(string.Join(", ", item)); } } }}