Net Core教程

C#求两数组相似度

本文主要是介绍C#求两数组相似度,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

// 用泛型委托实现对象的自定义比较。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CRApp
{
	static class Program
	{
		public delegate bool DLCompare<TValue>(TValue ValueA,TValue valueB);

		static int Main(string[] args)
		{
			string[] strA = { "apple", "boy", "cat" };
			string[] strB = { "apple", "bird", "cat" };
			Console.WriteLine("strA与strB的成员相似度为{0}%",CountSimilarity(strA, strB, delegate (string a, string b) { return (a == b); }));
			int[] numA = {1,4,5,7,9};
			int[] numB = {2,4,5,6,9};
			Console.WriteLine("numA与numB的成员相似度为{0}%",CountSimilarity(numA,numB,(_a,_b)=> { return (_a==_b);}));
			return (0);
		}

		public static double CountSimilarity<TArray> (TArray[] arrayA,TArray[] arrayB,DLCompare<TArray> compareDelegate)
		{
			if (arrayA == null || arrayB == null)
			{
				return (-1);
			}
			int[,] dp = new int[Math.Max(arrayA.Length,arrayB.Length)+1,Math.Max(arrayA.Length,arrayB.Length)+1];
			for (int a = 0; a < arrayA.Length; a++)
			{
				for (int b = 0; b < arrayB.Length; b++)
				{
					if (compareDelegate(arrayA[a],arrayB[b]))
					{
						dp[a + 1, b + 1] = dp[a, b] + 1;
					}
					else
					{
						dp[a + 1, b + 1] = Math.Max(dp[a, b + 1], dp[a + 1, b]);
					}
				}
			}
			return (Math.Round(((double)(dp[arrayA.Length, arrayB.Length]) / Math.Max(arrayA.Length, arrayB.Length)) * 100, 2));
		}
	}
}

/*
运行结果:
strA与strB的成员相似度为66.67%
numA与numB的成员相似度为60%
*/

这篇关于C#求两数组相似度的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!