重构笔记4-替换算法(substitute algorithm)

转自:http://www.cnblogs.com/matchcolor/archive/2010/07/26/1785604.html



你想要把某个算法替换为另一个更清晰地算法。将函数本体替换为另一个算法。   

string FoundPerson(string[] people)

        {

            for (int i = 0; i < people.Length; i++)

            {

                if (people[i].Equals("don"))

                {

                    return "don";

                }

                if (people[i].Equals("john"))

                {

                    return "john";

                }

                if (people[i].Equals("kent"))

                {

                    return "kent";

                }

            }

            return "";

        }

 

string FoundPerson(string[] people)

        {

            List<string> candidates = people.ToList<string>();

            for (int i = 0; i < candidates.Count; i++)

            {

                if (candidates.Contains(people[i]))

                {

                    return people[i];

                }

            }

            return "";

        }

动机:解决问题有好几种方法。算法也是如此。如果你发现做一件事可以有更清晰地方式,就应该以较清晰地方式取代复杂的方式。“重构”可以把一些复杂东西分解为较简单的小块,但有时你就必须删除整个算法,代之以简单的算法。随着对问题有了更多理解,你往往会发现,在原先的做法之外,有更简单的解决方案,此时就需要改变原来的算法。如果你开始使用程序库,而其中提供的某些功能/特性与你自己的代码重复,那么你也需要改变原先的算法。

       有时候你会想要修改原先的算法,让它去做一件与原先略有差异的事。这时候你也可以先把原先的算法替换为一个较易修改的算法,这样后续的修改会轻松许多。

       使用这项重构之前,请先确定自己尽可能分解了原先函数。替换一个巨大而复杂的算法是很困难的。只有先将它分解为较简单的小型函数,然后你才能很有把握的进行算法替换工作。

做法:1、准备好另一个算法,让它提供编译。

       2、针对现有测试,执行上述算法。如果结果与原本结果相同,重构结束。

       3、如果测试结果不同于原先,在测试和调试过程中,以旧算法为比较参照标准。对应每个测试用例,分别以新旧2种算法执行,并观察2者结果是否相同。这可以帮助你看到哪一个测试用例出现麻烦,以及出现了怎样的麻烦。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是基于多维样本空间分布密度的聚类中心优化K-均值算法的MATLAB代码,供参考: ```matlab function [label, center, obj_fcn] = kmeans_density(X, k) %KMEANS_DENSITY K-means clustering based on density distribution. % [LABEL, CENTER, OBJ_FCN] = KMEANS_DENSITY(X, K) partitions the points in the N-by-P % data matrix X into K clusters. Rows of X correspond to points, columns correspond % to variables. KMEANS_DENSITY returns an N-by-1 vector LABEL containing the cluster % indices of each point, a K-by-P matrix CENTER containing the coordinates of each % cluster center, and the objective function value OBJ_FCN of the final partition. % % KMEANS_DENSITY treats NaNs as missing data. Rows of X with NaNs are excluded from % the distance calculation. % % Example: % % % Generate some data points. % X = [randn(100,2)*0.75+ones(100,2); % randn(100,2)*0.5-ones(100,2)]; % % % Cluster the data points using K-means clustering based on density distribution. % [label, center] = kmeans_density(X, 2); % % % Plot the clustering result. % figure; % plot(X(label==1,1), X(label==1,2), 'r.', 'MarkerSize', 12); % hold on; % plot(X(label==2,1), X(label==2,2), 'b.', 'MarkerSize', 12); % plot(center(:,1), center(:,2), 'kx', 'MarkerSize', 15, 'LineWidth', 3); % legend('Cluster 1', 'Cluster 2', 'Centroids', 'Location', 'NW'); % title('K-means Clustering based on Density Distribution'); % hold off; % % See also KMEANS, KMEANS_DENSITY_D, KMEANS_DENSITY_N. % References: % [1] J. Shi and J. Malik, "Normalized Cuts and Image Segmentation," IEEE Transactions % on Pattern Analysis and Machine Intelligence, vol.22, no.8, pp.888-905, Aug. 2000. % [2] J. Shi and J. Malik, "Normalized Cuts and Image Segmentation," University of % California at Berkeley, Computer Science Division, Tech. Rep. #TR-00-01, 2000. % Copyright (c) 2013, Guangdi Li % Copyright (c) 2014, Guangdi Li % All rights reserved. % % Redistribution and use in source and binary forms, with or without modification, % are permitted provided that the following conditions are met: % % 1. Redistributions of source code must retain the above copyright notice, % this list of conditions and the following disclaimer. % % 2. Redistributions in binary form must reproduce the above copyright notice, % this list of conditions and the following disclaimer in the documentation % and/or other materials provided with the distribution. % % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND % ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED % WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. % IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, % INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, % BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, % OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, % WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY % OF SUCH DAMAGE. % Author: Guangdi Li, 2013-12-28 % Check inputs. narginchk(2,2); % n points in p-dimension space [n, p] = size(X); % Initialize some variables. label = zeros(n,1); last = zeros(n,1); center = X(randsample(n,k),:); obj_fcn = Inf; % Iterate until convergence. while any(label ~= last) % Save the last labels. last = label; % Compute the distance from each point to each center. distance = pdist2(X,center); % Compute the density distribution of each point. density = sum(exp(-distance.^2/(2*std2(distance)^2)),2); % Assign points to the nearest cluster. [~,label] = min(distance,[],2); % Reassign empty clusters. for j = find(histc(label,1:k)==0)' [~,i] = max(density.*(label==0)); label(i) = j; end % Compute the new centers. for j = 1:k center(j,:) = mean(X(label==j,:),1); end % Compute the objective function. obj_fcn = sum(sum((X - center(label,:)).^2)); end % Sort the centers by density distribution. [~,density] = sort(sum(exp(-distance.^2/(2*std2(distance)^2)),1),'descend'); center = center(density,:); end ``` 其中,`X` 是 $n \times p$ 的数据矩阵,`k` 是聚类的个数。函数返回聚类标签 `label`、聚类中心点 `center` 和聚类的目标函数值 `obj_fcn`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值