function [best_sol, best_cost] = go_mdmtsp(dist_matrix, n_iter, n_pop, n_child, prob_mut, size_pop)
% 初始化种群
pop = init_pop(size_pop, n_pop);
cost_pop = calc_cost_pop(dist_matrix, pop);
best_sol = pop(1,:);
best_cost = min(cost_pop);
for iter = 1:n_iter
% 选择操作
selected = select(pop, cost_pop, n_child);
% 交叉操作
offspring = cross(selected, dist_matrix, n_child);
% 变异操作
mutated = mutate(offspring, prob_mut, n_child);
% 计算变异后的成本
cost_mutated = calc_cost_pop(dist_matrix, mutated);
% 更新种群和成本
[pop, cost_pop] = update_pop(mutated, cost_mutated, pop, cost_pop, size_pop);
% 更新最佳解和成本
[best_sol, best_cost] = update_best(pop, cost_pop, best_sol, best_cost);
end
end
% 初始化种群
function pop = init_pop(size_pop, n_pop)
pop = randi([1,size_pop], n_pop, size_pop);
end
% 计算整个种群的成本
function cost_pop = calc_cost_pop(dist_matrix, pop)
cost_pop = cellfun(@(x) sum(dist_matrix(x,:)), pop);
end
% 选择操作
function selected = select(pop, cost_pop, n_child)
[~, I] = sort(cost_pop);
selected = pop(I(1:n_child),:);
end
% 交叉操作
function offspring = cross(selected, dist_matrix, n_child)
for i = 1:2:2*n_child-1
p1 = randi(n_child);
p2 = randi(n_child);
while p2 == p1
p2 = randi(n_child);
end
cross_points = randi(size(selected,2), 1, 2);
offspring(i,:) = [selected(p1,1:cross_points(1)) selected(p2,cross_points(1)+1:end)];
offspring(i+1,:) = [selected(p2,1:cross_points(1)) selected(p1,cross_points(1)+1:end)];
end
end
% 变异操作
function mutated = mutate(offspring, prob_mut, n_child)
for i = 1:n_child
for j = 1:size(offspring,2)
if rand < prob_mut
offspring(i,j) = randi([1,size(offspring,2)]);
end
end
end
end
% 更新种群和成本
function [pop, cost_pop] = update_pop(mutated, cost_mutated, pop, cost_pop, size_pop)
[~, I] = sort(cost_mutated);
pop(1:size_pop,:) = [mutated(I(1:size_pop),:) pop(size_pop+1:end,:)];
cost_pop(1:size_pop) = cost_mutated(I(1:size_pop));
end
% 更新最佳解和成本
function [best_sol, bes
题目描述:
给你一个由 '1'(岛屿)和 '0'(水)组成的的二维网格,请你返回网格中岛屿的数量。
示例 1:
输入:grid = [
["1","1","1","1","0"],["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
输出:1
示例 2:
输入:grid = [
["1","1","0","0","0"],["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
输出:3
提示:
- 1 <= grid.length, grid[0].length <= 100
- grid[i][j] 为 '0' 或 '1'
代码实现:
Java 实现:
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
count++;
infect(grid, i, j);
}
}
}
return count;
}
private void infect(char[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] != '1') {
return;
}
grid[i][j] = '2'; // 标记为 2 表示已经访问过
infect(grid, i + 1, j);
infect(grid, i - 1, j);
infect(grid, i, j + 1);
infect(grid, i, j - 1);
}
}
C 实现:
// C 语言实现需要补充内存管理和边界检查的代码
Python3 实现:
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
def infect(i, j):
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == '1':
grid[i][j] = '2'
infect(i + 1, j)
infect(i - 1, j)
infect(i, j + 1)
infect(i, j - 1)
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
count += 1
infect(i, j)
return count
Go 实现:
// Go 语言实现需要补充内存管理和边界检查的代码
以下是一个简化的解决方案,它展示了如何使用TypeScript来实现一个简单的二分查找函数:
function binarySearch(nums: number[], target: number): number {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const mid = left + ((right - left) >> 1);
if (nums[mid] === target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// 测试代码
const testNums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(binarySearch(testNums, 6)); // 输出: 5
console.log(binarySearch(testNums, -1)); // 输出: -1
这段代码实现了一个标准的二分查找算法,它接受一个排序好的数组和一个目标值,返回目标值在数组中的索引,如果不存在则返回-1。这个解决方案使用TypeScript的类型系统来确保函数的正确使用方式,并通过测试代码验证其功能。
题目描述:
给定一个学生信息列表,每个学生信息由姓名和身高组成。要找到身高最接近的小友。如果有多对小友身高相同,则输出字典序最小的一对。
输入描述:
学生信息列表,每个学生信息由姓名和身高组成,姓名和身高由空格分隔,学生信息由换行分隔。
输出描述:
找到身高最接近的小友的信息,姓名和身高之间用空格分隔。
示例输入:
Bob 120
Alice 130
Jane 110
示例输出:
Jane 110 Bob 120
解决方案:
Java 代码实现:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Student> students = new ArrayList<>();
while (scanner.hasNextLine()) {
String[] info = scanner.nextLine().split(" ");
students.add(new Student(info[0], Integer.parseInt(info[1])));
}
Student[] closestFriends = findClosestFriends(students);
System.out.println(closestFriends[0].name + " " + closestFriends[0].height + " " + closestFriends[1].name + " " + closestFriends[1].height);
}
private static Student[] findClosestFriends(List<Student> students) {
students.sort(Comparator.comparingInt(s -> s.height));
int minDiff = Integer.MAX_VALUE;
Student[] closest = new Student[2];
for (int i = 1; i < students.size(); i++) {
int diff = Math.abs(students.get(i).height - students.get(i - 1).height);
if (diff < minDiff) {
minDiff = diff;
closest[0] = students.get(i - 1);
closest[1] = students.get(i);
}
}
return closest;
}
static class Student {
String name;
int height;
public Student(String name, int height) {
this.name = name;
this.height = height;
}
}
}
Python 代码实现:
import sys
def find_closest_friends(students):
students.sort(key=lambda s: s.height)
min_diff = sys.maxsize
closest = [None, None]
for i in range(1, len(students)):
diff = abs(students[i].height - students[i - 1].height)
if diff < min_diff:
min_diff = diff
closest[0] = students[i - 1]
closest[1] = students[i]
return closest
class Student:
def __init__(self, name, height):
self.name = name
self.height = height
if __name__ == "__main__":
students = []
for line in sys.stdin:
name, height = line.split()
students.append(Student(name, int(height)))
closest_friends = find_closest_friends(students)
print(f"{closest_friends[0].name} {
题目描述:
给定一个正整数 n ,请找出跳格子的方式数,跳格子的规则是每次只能跳至正向的下一个格子,或是跳至负向的下一个格子。
输入描述:
输入一个正整数 n
输出描述:
输出跳格子的方式数
解决方案:
这是一个典型的动态规划问题。我们可以定义一个数组 dp ,其中 dp[i] 表示到达格子 i 的方式数。初始时,dp 数组中的所有元素都初始化为0。
动态规划的状态转移方程为:
- 如果 i 是偶数,那么 dp[i] = dp[i - 1] + dp[i / 2],表示可以从 i - 1 直接跳到 i,或者从 i / 2 经过一次跳跃后到达 i。
- 如果 i 是奇数,那么 dp[i] = dp[i - 1],表示因为只能跳至正向的下一个格子或负向的下一个格子,所以无论如何我们都不能到达奇数位置的格子。
以下是各种语言的实现:
Java 实现:
public class Main {
public static void main(String[] args) {
int n = 5; // 示例输入
System.out.println(jumpFloor(n));
}
public static int jumpFloor(int target) {
if (target <= 0) {
return 0;
}
int[] dp = new int[target + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= target; i++) {
if (i % 2 == 0) {
dp[i] = dp[i - 1] + dp[i / 2];
} else {
dp[i] = dp[i - 1];
}
}
return dp[target];
}
}
Python 实现:
def jumpFloor(target):
dp = [0] * (target + 1)
dp[0], dp[1] = 0, 1
for i in range(2, target + 1):
if i % 2 == 0:
dp[i] = dp[i - 1] + dp[i // 2]
else:
dp[i] = dp[i - 1]
return dp[target]
print(jumpFloor(5)) # 示例输出
C++ 实现:
#include <iostream>
#include <vector>
using namespace std;
int jumpFloor(int target) {
vector<int> dp(target + 1, 0);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= target; i++) {
if (i % 2 == 0) {
dp[i] = dp[i - 1] + dp[i / 2];
} else {
dp[i] = dp[i - 1];
}
}
return dp[target];
}
int main() {
int n;
cin >> n;
cout << jumpFloor(n) << endl;
return 0;
}
JavaScript 实现:
function jumpFloor(target) {
let dp = new Array(target + 1).fill(0);
dp[0] = 0;
dp[1] = 1;
for (let i = 2; i <= target; i++) {
if (i % 2 === 0) {
PyCryptodome是一个Python库,提供了一系列加密算法,包括对称加密、非对称加密以及哈希算法等。它是PyCrypto的一个分支版本,并且继续被维护。
以下是一些使用PyCryptodome库进行加密的示例代码:
- 使用AES进行对称加密:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
key = get_random_bytes(16) # 生成一个16字节的密钥
cipher = AES.new(key, AES.MODE_EAX) # 创建一个新的AES密码算法实例
data = b"secret data" # 需要加密的数据
ciphertext, tag = cipher.encrypt_and_digest(data) # 执行加密操作
# 保存密钥和加密数据
print("Cipher:", cipher.name)
print("Tag:", tag)
print("Ciphertext:", ciphertext)
- 使用RSA进行非对称加密:
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
rsa = RSA.generate(2048) # 生成一个2048位的公钥
public_key = rsa.publickey()
data = b"secret data" # 需要加密的数据
# 使用公钥加密数据
cipher = PKCS1_OAEP.new(public_key)
encrypted = cipher.encrypt(data)
# 保存公钥和加密数据
print("Public key:", public_key.export_key())
print("Encrypted data:", encrypted)
- 使用SHA256进行哈希加密:
from Crypto.Hash import SHA256
message = b"secret data" # 需要哈希的数据
# 创建哈希对象并更新数据
hasher = SHA256.new()
hasher.update(message)
# 获取哈希值
print("Digest:", hasher.digest())
这些示例展示了如何使用PyCryptodome库中的不同加密算法进行数据加密、解密、签名和验证。在实际应用中,你需要根据具体需求选择合适的算法,并确保安全性、完整性和保密性。
雪花算法(Snowflake)是一种用于生成分布式唯一ID的算法,它能够保证在分布式系统中每个节点每秒钟生成数十亿的唯一ID,且这些ID按照时间的顺序排序。
在JavaScript中,由于Number类型的精度限制,如果直接使用雪花算法生成的64位ID,可能会丢失精度,导致ID不能正确表示。因此,需要对雪花算法的位数进行适当的改造,以确保在JavaScript中能够正确地表示和使用这些ID。
以下是一个改造后的53bit分布式ID生成器的示例代码:
class Snowflake {
constructor() {
this.epoch = 1577836800000; // 自定义起始时间(毫秒)
this.lastTimestamp = -1;
this.sequence = 0;
this.nodeId = 0; // 节点ID
}
/**
* 生成新的ID
*/
nextId() {
let timestamp = Date.now();
let timestampDiff = timestamp - this.epoch;
if (timestampDiff >= 2 ** 42) {
throw new Error('Timestamp bits are exhausted');
}
let sequenceBits = 13;
let nodeIdBits = 10;
let id = (timestampDiff << (sequenceBits + nodeIdBits)) +
(this.nodeId << sequenceBits) +
(this.sequence & ((1 << sequenceBits) - 1));
if (this.lastTimestamp === timestamp) {
this.sequence = (this.sequence + 1) & ((1 << sequenceBits) - 1);
if (this.sequence === 0) {
// 等待下一个毫秒
throw new Error('Sequence bits are exhausted');
}
} else {
this.sequence = 0;
}
this.lastTimestamp = timestamp;
return id;
}
}
// 使用示例
const snowflake = new Snowflake();
const id = snowflake.nextId();
console.log(id);
在这个改造后的版本中,我们使用了JavaScript的Number类型来表示ID,但是限制了时间戳、序列号和节点ID的位数,以确保在JavaScript中不会因为Number类型的精度问题而导致ID的丢失。这样,我们就可以在JavaScript环境中使用雪花算法生成的53bit分布式ID了。
package main
import (
"fmt"
"math/rand"
"time"
)
// 定义城市坐标结构体
type City struct {
x, y float64
}
// 定义遗传算法解决旅行商问题的结构体
type GA struct {
population [][]City
nextCity []City
best []City
fitness float64
size int
mutation float64
crossover float64
elitism bool
}
// 初始化遗传算法
func (ga *GA) Init(size int, mutation, crossover float64, elitism bool) {
ga.size = size
ga.mutation = mutation
ga.crossover = crossover
ga.elitism = elitism
ga.population = make([][]City, size)
ga.best = make([]City, len(cities))
for i := range ga.population {
ga.population[i] = make([]City, len(cities))
for j := range ga.population[i] {
ga.population[i][j] = cities[j]
}
rand.Shuffle(len(ga.population[i]), func(i, j int) {
ga.population[i][i], ga.population[i][j] = ga.population[i][j], ga.population[i][i]
})
}
}
// 计算适应度函数
func (ga *GA) Fitness() {
var total float64
for i := range ga.population {
var distance float64
for j := 1; j < len(ga.population[i]); j++ {
distance += Distance(ga.population[i][j-1], ga.population[i][j])
}
distance += Distance(ga.population[i][len(ga.population[i])-1], ga.population[i][0])
if distance < ga.fitness || ga.fitness == 0 {
copy(ga.best, ga.population[i])
ga.fitness = distance
}
total += distance
}
fmt.Println("Best fitness:", ga.fitness)
}
// 交叉操作
func (ga *GA) Crossover() {
for len(ga.population) < cap(ga.population) {
parent1 := rand.Intn(len(ga.population))
parent2 := rand.Intn(len(ga.population))
if rand.Float64() < ga.crossover {
crossPoint := rand.Intn(len(ga.population[parent1])-1) + 1
ga.population = append(ga.population, append(ga.population[parent1][crossPoint:], ga.population[parent2][:crossPoint]...))
}
}
}
// 变异操作
func (ga *GA) Mutation() {
for i := range ga.population {
for j := range ga.population[i] {
if rand.Float64() < ga.mutation {
rand.Shuffle(len(ga.population), func(i, j int) {
ga.population[i][j], ga.population[i][j] = ga.population[i][j], ga.population[i][i]
})
}
}
}
}
// 选择操作
func (ga *GA) Selection() {
newPopulation := make(
思维导图和字数限制,无法提供完整的jQuery基础思维导图和实例代码。但我可以提供一个简单的jQuery代码示例,它展示了如何选择一个元素并改变其背景颜色:
// 确保DOM完全加载
$(document).ready(function() {
// 选择ID为"myElement"的元素
$('#myElement').css('background-color', 'yellow');
});
这段代码使用了jQuery的$(document).ready()
方法来确保在DOM完全加载后执行代码,$('#myElement')
选择了ID为myElement
的DOM元素,并使用.css()
方法更改了其背景颜色。
在MATLAB中,可以使用以下代码实现基于改进蚁群算法的电源选址和定容研究:
% 初始化参数
numSites = 100; % 站点数量
numBuses = 1000; % 总总线数量
maxIter = 500; % 最大迭代次数
alpha = 0.3; % 电网拓扑结构参数
beta = 0.6; % 电网拓扑结构参数
rho = 0.1; % 电网拓扑结构参数
Q = 100; % 总需求量
% 初始化电源和线路容量
powerC = rand(numSites, 1) * 100; % 初始电源容量
busC = zeros(numBuses, 1); % 初始总线容量
% 初始化电源和线路流量
powerFlow = zeros(numSites, 1); % 电源流量
busFlow = zeros(numBuses, 1); % 总线流量
% 初始化电源和线路连接矩阵
connMatrix = rand(numSites, numSites); % 随机初始连接矩阵
% 迭代求解
for iter = 1:maxIter
% 更新电源容量
powerC = alpha * powerC .* (1 + beta * rand(numSites, 1));
% 更新电源和总线流量
for i = 1:numSites
powerFlow(i) = sum(connMatrix(i, :)) * powerC(i);
busFlow = sum(connMatrix, 2);
end
% 更新总线容量
busC = busFlow .* rho;
% 检查是否满足需求
if sum(powerC) >= Q
% 如果满足需求则结束迭代
break;
end
end
% 输出结果
disp(['最佳电源容量: ', num2str(powerC)]);
disp(['最佳总线容量: ', num2str(busC)]);
% 可以添加代码绘制电源容量和总线容量的变化曲线等进行可视化分析
这段代码实现了基于改进蚁群算法的电源选址和定容的初步框架。在实际应用中,可以添加更多细节,例如电源布置的随机性引入、电网拓扑结构的具体实现、电源容量和总线容量的可视化分析等。