分类
未分类

遗传算法

// C++ program to create target string, starting from
// random string using Genetic Algorithm
#include <iostream>
#include <queue>
#include <cstdlib>
#include <string>
#include <stack>
using namespace std;
#define MAX_VERTEX_NUM 30
#define POPULATION_SIZE 100
#define  TARGET_SIZE 7</stack></string></cstdlib></queue></iostream>

bool visited[MAX_VERTEX_NUM];
double ve[MAX_VERTEX_NUM];
double vl[MAX_VERTEX_NUM];
stack<int> T;
// Valid Genes
vector<int> GENES = {2,2,2,2};</int></int>

typedef struct ArcNode{
int adjvex;
struct ArcNode* next;
double time;
bool key;
}ArcNode;
typedef struct VNode{
int data;
ArcNode *first;
int machine;
}VNode,AdjList[MAX_VERTEX_NUM];

typedef struct {
AdjList vertices;
int vexnum,arcnum;
int indegree[MAX_VERTEX_NUM];
}ALGraph;

ALGraph graph;

bool Visit(ALGraph G,int v)
{
printf("%d",G.vertices[v].data);
return true;
}

void dfs(ALGraph G,int v)
{
visited[v]=true;
Visit(G,v);
ArcNode* ptr;
for(ptr=G.vertices[v].first;ptr != nullptr;ptr=ptr-&gt;next)
{
if(!visited[ptr-&gt;adjvex])
dfs(G,ptr-&gt;adjvex);
}
}

void dfsTraverse(ALGraph G)
{
int v;
for(v=0;v<g.vexnum;v++) visited[v]="false;" for(v="0;v<G.vexnum;v++)" if(!visited[v])="" dfs(g,v);="" }="" void="" bfstraverse(algraph="" g)="" {="" for(int="" v="0;v<G.vexnum;v++)" queue<int=""> Q;
for(int v=0;v<g.vexnum;v++) {="" if(!visited[v])="" visited[v]="true;" visit(g,v);="" q.push(v);="" while(!q.empty())="" int="" m;="" m="Q.front();" q.pop();="" arcnode*="" ptr="G.vertices[m].first;" for(;ptr!="nullptr;ptr=ptr-">next)
{
if(!visited[ptr-&gt;adjvex])
{
visited[ptr-&gt;adjvex]=true;
Visit(G,ptr-&gt;adjvex);
Q.push(ptr-&gt;adjvex);
}
}
}
}
}
}</g.vexnum;v++)></g.vexnum;v++)>

void findIndegree(ALGraph&amp; G)
{
int i,j,k;
for(int mm=0;mm<g.vexnum;mm++) g.indegree[mm]="0;" for(i="0;i<G.vexnum;i++)" {="" arcnode*="" arc="G.vertices[i].first;" for(;arc="" !="nullptr;arc=arc-">next)
{
G.indegree[arc-&gt;adjvex]++;
}
}
}</g.vexnum;mm++)>

bool TopologicalOrder(ALGraph G,stack<int>&amp;tt)
{
//求各顶点事件的最早发生时间
int indegree[G.vexnum],count=0;
ArcNode* ptr;
findIndegree(G);
queue<int> S;
for(int ii=0;ii<g.vexnum;ii++) {="" if(g.indegree[ii]="=0)" s.push(ii);="" }="" for(int="" loop="0;loop<G.vexnum;loop++)" ve[loop]="0;" while(!s.empty())="" int="" jj="S.front();" s.pop();="" tt.push(jj);="" count++;="" ptr="G.vertices[jj].first;" for(;ptr="" !="nullptr;ptr=ptr-">next)
{
int k=ptr-&gt;adjvex;
if(--G.indegree[k]==0){
S.push(k);
}
if(ve[jj]+ptr-&gt;time&gt;ve[k])
ve[k]=ve[jj]+ptr-&gt;time;
}
}
return count == G.vexnum;
}</g.vexnum;ii++)></int></int>

double criticalPath(ALGraph&amp; G)
{
ArcNode* ptr;
int path=0,count=0;
double time=0;
for(int tt=0;tt<g.vexnum;tt++) {="" ptr="G.vertices[tt].first;" for(;ptr;ptr="ptr-">next)
{
ptr-&gt;time=0;
ptr-&gt;key= false;
}
}
if(!TopologicalOrder(G,T))
{
return false;
}
int i,k;
for(i=0;i<g.vexnum;i++) {="" vl[i]="ve[G.vexnum-1];" }="" while(!t.empty())="" int="" j="T.top();" t.pop();="" for(ptr="G.vertices[j].first;ptr;ptr=ptr-">next)
{
k=ptr-&gt;adjvex;
double dut=ptr-&gt;time;
if(vl[k]-dut<vl[j]) vl[j]="vl[k]-dut;" }="" for(i="0;i<G.vexnum;i++)" {="" for(ptr="G.vertices[i].first;ptr;ptr=ptr-">next)
{
k=ptr-&gt;adjvex;
double dut=ptr-&gt;time;
double ee=ve[i],el=vl[k]-dut;
char tag=(ee==el)?'*':' ';
if(tag=='*'){
ptr-&gt;key=true;
time+=ptr-&gt;time;
}
}
}
return time;
}</vl[j])></g.vexnum;i++)></g.vexnum;tt++)>

void Create_Graph(vector<int> gron)
{
int i,j,k;
int count=0;
ArcNode* ptr;
for(i=0;i<graph.vexnum;i++) {="" ptr="graph.vertices[i].first;" for(;ptr;ptr="ptr-">next)
{
ptr-&gt;time=gron[count];
count++;
}
}
}</graph.vexnum;i++)></int>

// Number of individuals in each generation

#define ITERATION_MAX 400

// Target string to be generated
//const int TARGET = 0;

// Function to generate random numbers in given range
int random_num(int start, int end)
{
int range = (end-start)+1;
int random_int = start+(rand()%range);
return random_int;
}

// Create random genes for mutation
int mutated_genes()
{
int len = GENES.size();
int r = random_num(0, len-1);
return GENES[r];
}

// create chromosome or string of genes
vector<int> create_gnome()
{
int len = TARGET_SIZE;
vector<int> gnome;
for(int i = 0;i<len;i++) gnome.push_back(mutated_genes());="" return="" gnome;="" }="" class="" representing="" individual="" in="" population="" {="" public:="" vector<int=""> chromosome;
double fitness;
Individual(vector<int> chromosome);
Individual mate(Individual parent2);
double cal_fitness();
};</int></len;i++)></int></int>

Individual::Individual(vector<int> chromosome)
{
this-&gt;chromosome = chromosome;
//  Create_Graph();
fitness = cal_fitness();
};</int>

// Perform mating and produce new offspring
Individual Individual::mate(Individual par2)
{
// chromosome for offspring
vector<int> child_chromosome;</int>

int len = chromosome.size();
for(int i = 0;i<target_size;i++) {="" random="" probability="" float="" p="random_num(0," 100)="" 100;="" if="" prob="" is="" less="" than="" 0.45,="" insert="" gene="" from="" parent="" 1="" if(p="" <="" 0.45)="" child_chromosome.push_back(chromosome[i]);="" between="" 0.45="" and="" 0.90,="" 2="" else="" 0.90)="" child_chromosome.push_back(par2.chromosome[i]);="" otherwise="" gene(mutate),="" for="" maintaining="" diversity="" child_chromosome.push_back(mutated_genes());="" }="" create="" new="" individual(offspring)="" using="" generated="" chromosome="" offspring="" return="" individual(child_chromosome);="" };="" calculate="" fittness="" score,="" it="" the="" number="" of="" characters="" in="" string="" which="" differ="" target="" string.="" double="" individual::cal_fitness()="" create_graph(this-="">chromosome);
int i,j,k,count=0;
fitness=0;
for(i=0;i<graph.vexnum;i++) {="" graph.vertices[i].machine="chromosome[i];" arcnode*="" ptr="graph.vertices[i].first;" for(;ptr;ptr="ptr-">next)
{
ptr-&gt;time=graph.vertices[i].data*1.0/GENES[graph.vertices[i].machine];
}
}
fitness=criticalPath(graph);
return fitness;
};</graph.vexnum;i++)></target_size;i++)>

// Overloading &lt; operator
bool operator&lt;(const Individual &amp;ind1, const Individual &amp;ind2)
{
    return ind1.fitness &lt; ind2.fitness;
}

// Driver code
int main()
{
    srand((unsigned)(time(nullptr)));
    graph.vexnum=7;
    graph.arcnum=9;
    int m,n;
    ArcNode* ptr;
    int edge[9][2]={{0,1},{0,2},{1,3},{1,4},{2,3},{2,5},{3,5},{4,5},{5,6}};
    int data[7]={1,3,4,5,6,3,0};
    for(int i=0;i<graph.vexnum;i++) {="" graph.vertices[i].data="data[i];" graph.vertices[i].first="nullptr;" }="" for(auto="" &="" i="" :="" edge)="" m="i[0];" n="i[1];" ptr="(ArcNode*)malloc(sizeof(ArcNode));" ptr-="">adjvex=n;
ptr-&gt;next = graph.vertices[m].first;
graph.vertices[m].first=ptr;
}</graph.vexnum;i++)>

//    criticalPath(graph);
// current generation
int generation = 0;

vector<individual> population;
bool found = false;</individual>

// create initial population
for(int i = 0;i<population_size;i++) {="" vector<int=""> gnome = create_gnome();
population.push_back(Individual(gnome));
}</population_size;i++)>

while(! found)
{
// sort the population in increasing order of fitness score
sort(population.begin(), population.end());

// if the individual having lowest fitness score ie.
// 0 then we know that we have reached to the target
// and break the loop
if(population[0].fitness &lt;= 0||generation==4000)
        {
            found = true;
            break;
        }

        // Otherwise generate new offsprings for new generation
        vector<individual> new_generation;</individual>

// Perform Elitism, that mean 10% of fittest population
// goes to the next generation
int s = (10*POPULATION_SIZE)/100;
for(int i = 0;i<s;i++) new_generation.push_back(population[i]);="" from="" 50%="" of="" fittest="" population,="" individuals="" will="" mate="" to="" produce="" offspring="" s="(90*POPULATION_SIZE)/100;" for(int="" i="0;i<s;i++)" {="" int="" len="population.size();" r="random_num(0," 50);="" individual="" parent1="population[r];" parent2="population[r];" new_generation.push_back(offspring);="" }="" population="new_generation;" cout<<="" "generation:="" "="" <<="" generation="" "\t";="" "string:="" "<<="" population[0].chromosome="" <<"\t";="" "fitness:="" population[0].fitness="" "\n";="" generation++;="" ccc="0;" printf("\n*******************\n");="" ii="0;ii<graph.vexnum;ii++)" printf("%d*",graph.vertices[ii].machine);="" <="" code=""></s;i++)>
分类
博客搭建

小白搭建博客超详细教程~

前沿:一周前搭好了自己的博客,正好身边有朋友的作业是搭建博客,为此她也十分苦恼(?),所以写了一个教程,希望能帮助到有需要的人。

博客三要素:服务器、域名、界面

总花费:一周空余时间+18元(抠门达人哈哈哈哈)

一、服务器

介绍:轻量级服务器

购买网址:阿里云学生机购买入口

1、如图,点击轻量应用服务器

2、地区选择华北、选择系统镜像->CentOS,其余为默认值

3、返回阿里云首页,并选择轻量应用服务器控制台

4、点击进入控制台

5、会看到自己新买的服务器列表(这里默认叫CentOS)

6、先回到阿里云控制台,在左侧点击远程连接

7、首先在命令行输入

sudo su root
切换至root账号

8、继续输入

yum install -y wget && wget -O install.sh http://download.bt.cn/install/install_6.0.sh && sh install.sh

等待,其间需要输入y确认

9、安装成功 显示公网(外网)网址,用户名以及密码

服务器告一段落

二、域名

1、购买域名

分类
iOS学习

swift CardView踩过的大坑

如题 做一个swift卡片

1、别问,问就是踩了大坑

呜呜呜 TableView cell 的contentView 默认高度是44 我以为是行高

let cell = tableView.dequeueReusableCell(withIdentifier: "NewsList", for: indexPath)

let cell = NewsListTableViewCell(style: .default, reuseIdentifier: "NewsList")//这个是代码

这两个方法有什么区别吗? 觉得第一个方法不用也罢

2、别问,问就是 CellForRowAtIndexPath不执行,原因如下:

1.没有设置代理或设置的代理有问题。

2.代理方法,返回行数或者组数可能为0

3、去除分割线

Swift中设置tableview的分割线(separator)的样式、颜色、边距

    //设置分割线样式
    // 三种分割线样式:
    // case None  无分割线
    // case SingleLine 单条分割线
    // case SingleLineEtched // This separator style is only supported for grouped style table views currently

    self.tableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
    //设置分割线颜色
    self.tableView.separatorColor = UIColor.redColor()
    //设置分割线内边距
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)

4、关于执行顺序的问题

provider.request()函数是一个逃逸闭包,在ViewDidLoad()函数最后执行,因此

1、tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 函数必须分有无数据情况讨论

2、必须在getData()中加入reloadData()

分类
iOS学习

swift 处理Moya数据

如题,处理moya数据

1、提取成功代码

2、转化为json(利用mapString)

3、转化为对象数组(利用JSONDecoder().decode)

let respose = try  moyaResponse.filterSuccessfulStatusCodes()
let jsonString = try respose.mapString()
let userData: [UserData] = try JSONDecoder().decode([UserData].self, from:jsonString.data(using: .utf8)!)
分类
iOS学习

swift 滚动分段控制器

将ScrollView与SegmentedControl结合使用

视频加载不出来,看了个寂寞(

import UIKit
import Moya
class ViewController: UIViewController {
    var headerSeg = UISegmentedControl(items: [ "通知公告","学籍管理","考试管理","排课选课"
    ,"成绩管理","毕业管理","实践教学","毕业设计","学科竞赛","综合管理"])
    var scrollView = UIScrollView()
    var newslistModel : [MyNewsListModel] = []
    let provider = MoyaProvider<MyNewsListTarget>()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "资讯"
        self.view.backgroundColor = .white
        setLayout()
        self.headerSeg.addTarget(self, action: #selector(tapped), for: .valueChanged)
    }
    
    func setLayout()
    {
        self.headerSeg.frame.origin = CGPoint(x: 0, y: 0)
        self.headerSeg.frame.size.height = 50.0
        self.headerSeg.frame.size.width = 125.0*10
//        self.scrollView.frame.origin = CGPoint(x: 0, y: (self.navigationController?.navigationBar.frame.height ?? 80) + 20)
        self.scrollView.frame = CGRect(x: 0, y: ((self.navigationController?.navigationBar.frame.height ?? 80) + 20), width: self.view.bounds.width, height: 50)
        self.view.addSubview(self.scrollView)
        self.scrollView.addSubview(self.headerSeg)
        scrollView.isScrollEnabled = false
        for i in 0...9
        {
            headerSeg.setWidth(125, forSegmentAt: i)
        }
         self.scrollView.contentSize = CGSize(width: headerSeg.widthForSegment(at: 1)*20, height: 50)
    }
    
    @objc func tapped()
    {
        switch self.headerSeg.selectedSegmentIndex {
        case 0:
            self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        case 1:
            self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        case 2:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1), y: 0), animated: true)
        case 3:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*2, y: 0), animated: true)
        case 4:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*3, y: 0), animated: true)
        case 5:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*4, y: 0), animated: true)
        case 6:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*5, y: 0), animated: true)
        case 7:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*6, y: 0), animated: true)
        case 8:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*7, y: 0), animated: true)
        case 9:
            self.scrollView.setContentOffset(CGPoint(x: headerSeg.widthForSegment(at: 1)*7, y: 0), animated: true)
        default:
            return
        }
    }
    
}
分类
iOS学习

Xcode 11新建swift 项目

如题 新建swift项目

1、在AppDelegate中声明window属性

2、AppDelegate中两个关于Scene的类添加版本控制,用扩展单独拎出来

@UIApplicationMain
 
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
 
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        if #available(iOS 13, *) {
        }else {
            window = UIWindow.init()
            window?.frame = UIScreen.main.bounds
            window?.makeKeyAndVisible()
            window?.rootViewController = UIViewController.init()
        }
        return true
        
    }
}
 
@available(iOS 13.0, *)
extension AppDelegate {
    // MARK: UISceneSession Lifecycle
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }
 
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    }
}

3、SceneDelegate中添加版本控制

import UIKit
@available(iOS 13, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
 
    var window: UIWindow?
 
 
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
        let windowScene:UIWindowScene = scene as! UIWindowScene
        window = UIWindow.init(windowScene: windowScene)
        window?.backgroundColor = UIColor.green
        window?.frame = UIScreen.main.bounds
        window?.makeKeyAndVisible()
        let tt = UIViewController.init()
        tt.view.backgroundColor = UIColor.brown
        window?.rootViewController = tt
        guard let _ = (scene as? UIWindowScene) else { return }
    }
}

分类
未分类

同行们,您好!

这是我的第一篇WordPress博客哇哇哇~