别再死磕梯度下降了!用Python手搓一个禁忌搜索算法(TS)解决你的组合优化难题
2026/5/11 23:54:34
js
// map 平方 let arr = [1,2,3,4]; let res1 = arr.map(x => x*x); // filter 偶数 let res2 = arr.filter(x => x % 2 === 0); // reduce 求和 let res3 = arr.reduce((sum, x) => sum + x, 0); console.log(res1, res2, res3);java
运行
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { List<Integer> list = Arrays.asList(1,2,3,4); // map 平方 List<Integer> res1 = list.stream().map(x -> x*x).collect(Collectors.toList()); // filter 偶数 List<Integer> res2 = list.stream().filter(x -> x%2==0).collect(Collectors.toList()); // reduce 求和 int sum = list.stream().reduce(0, Integer::sum); } }csharp
运行
using System; using System.Linq; class Program { static void Main() { int[] arr = {1,2,3,4}; // map 平方 var res1 = arr.Select(x => x*x); // filter 偶数 var res2 = arr.Where(x => x%2 == 0); // reduce 求和 int sum = arr.Aggregate(0, (s,x) => s + x); } }go
运行
package main import "fmt" // 高阶函数:函数当参数 func mapSlice(arr []int, f func(int)int) []int { res := make([]int, len(arr)) for i, v := range arr { res[i] = f(v) } return res } func main() { arr := []int{1,2,3,4} // 传匿名函数 res := mapSlice(arr, func(x int) int { return x * x }) fmt.Println(res) }cpp
运行
#include <iostream> #include <vector> #include <algorithm> #include <numeric> using namespace std; int main() { vector<int> arr = {1,2,3,4}; vector<int> res; // transform 等价map transform(arr.begin(), arr.end(), back_inserter(res), [](int x){ return x*x; }); // 求和 reduce int sum = accumulate(arr.begin(), arr.end(), 0); return 0; }