ShiShuo 2020-03-05
1、原题
2、代码
@A = (5,6,7); # 数组用@和圆括号,用$A[index]访问;哈希用%和圆括号,用 # $A{‘key‘}访问 @B = (6,7,8); @intersection; @union; # 计算交集,依次取出A中元素,判断其是否与B中的某个元素相等 foreach $a (@A){ for($i=0;$i<@B;$i++){ # @B的含义由上下文决定,此处表示其size if($B[$i] == $a){ push(@intersection,$a); } } } print("intersection is:\n"); foreach $item (@intersection){ print("$item "); } print("\n"); # 计算并集,先将A和B直接合并,接着依次判断A_B中的各个元素是否已经存在于 # 当前的union数组中,若没有则push进去 @A_B = (@A,@B); for $item (@A_B){ $item_in_current_union = 0; for($i=0;$i<@union;$i++){ if($union[$i]==$item) { $item_in_current_union = 1; } } if($item_in_current_union == 0){ push(@union,$item); $size = @union; # union的大小动态改变 print("union size is $size\n"); } } print("union is:\n"); foreach $item (@union){ print("$item "); } print("\n");
3、输出
intersection is: 6 7 union size is 1 union size is 2 union size is 3 union size is 4 union is: 5 6 7 8