首页 > 编程语言 > 详细

lua里面求int数组的union,diff,inter,distinct 方法实现

时间:2016-01-09 21:25:44      阅读:287      评论:0      收藏:0      [点我收藏+]
function lua_union(union_source,union_target)
    if type(union_source)~=table or type(union_target)~=table then
        return {};
    end;
    if #(union_source)==0 and #(union_target)==0 then
        return {};
    end;
    for i=1,#(union_target) do
        local flag=true;
        for j=1,#(union_source) do
            if union_target[i]==union_source[j] then
                flag=false;
                break;
            end;
        end;
        if flag==true then
            table.insert(union_source,union_target[i])
        end;
    end;
    return union_source;
end;

function lua_diff(diff_source,diff_target)
    if type(diff_source)~=table or type(diff_target)~=table then
        return {};
    end;
    if #(diff_source)==0 and #(diff_target)==0 then
        return {};
    end;
    for i=#(diff_source),1,-1 do
        for j=1 ,#(diff_target) do
            if diff_source[i]==diff_target[j] then
                table.remove(diff_source,i);
            end;
        end;
    end;
    return diff_source;
end;

function lua_distinct(distinct_source)
    if type(distinct_source)~=table then
        return {};
    end;
    for i=1,#(distinct_source) do
        for j=#(distinct_source),i+1,-1 do
            if distinct_source[i]==distinct_source[j] then
                table.remove(distinct_source,j);
            end;
        end;    
    end;
    return distinct_source;
end;

function lua_inter(inter_source,inter_target)
    if type(inter_source)~=table or type(inter_target)~=table then
        return {};
    end;
    for i=#(inter_source),1,-1 do
        for j=1,#(inter_target) do
            if inter_source[i]==inter_target[j] then
                table.remove(inter_source,i);
            end;
        end;
    end;
    return inter_source;
end;

local result1=lua_union({},{3,3});
local result2=lua_diff({1,2,3,4,5},{2,3});
local result3=lua_distinct({1,1,2,1}) ;
local result4=lua_inter({1,2,3,4,5},{1,2});

 

lua里面求int数组的union,diff,inter,distinct 方法实现

原文:http://www.cnblogs.com/fengxiaoling/p/5117181.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!