自己项目中的一些算法处理

来源:互联网 发布:霍尼韦尔口罩与3m 知乎 编辑:程序博客网 时间:2024/06/06 18:11

算法无处不在,用学校教务系统的时候发现了一个漏洞,于是写了个程序,通过学号把照片给爬下来了,因为并不知道学校的学号编制,所以只好先通过图片是否能正确获取来判断学号是否有效,但是因为并不是逐1遍历的,并且不是一次性爬完,所以数据存在冗余,并且数据乱序,所以数据样本可以形容成一个无序,可能含有重复数字的数据,


剔除重复数据,这个就相当于是“a.txt文件中存在大量数据,每个数据之间通过;隔开,查找出其中重复的数据并存储在b.txt中”。

首先想到的是读取文件后,装入vector 然后类似冒泡法一样逐一遍历删除重复数据,然后写着写着发现可以直接插入的时候就用二叉查找树来装,这样也方便了排序问题



#include "stdafx.h"#include <string>#include <vector>#include <iostream>#include <fstream>#include <stdio.h>using namespace std;typedef struct BTreeNode{BTreeNode* lChild;BTreeNode* rChild;string *data;}BNode,*BinSearchTree;int myCompare(string str1,string str2){int iStr1,iStr2;iStr1=atoi(str1.c_str());iStr2 = atoi(str2.c_str());if (iStr1 == iStr2)        return 0;else if(iStr1>iStr2)return 1;else if(iStr1<iStr2)return -1;return 2;}void insertNode(BinSearchTree *root,string str){if ( *root == NULL){BNode* node = (BNode*)malloc(sizeof(BNode));node->data = new string(str);node->lChild =NULL;node->rChild =NULL;*root = node;}else{int i = myCompare( ( *( *root)->data),str);if ( -1==i)insertNode(&((*root)->rChild),str);else if( 0 == i)return;else if(1 ==i)insertNode(&((*root)->lChild),str);}}void printTree(BinSearchTree T){if (T !=NULL){printTree(T->lChild);FILE* fp = fopen("D:\\b.txt","a+");fwrite(( *(T->data) ).c_str(), 1,( *(T->data) ).length(),fp);fwrite("\n",1,1,fp);fclose(fp);printTree(T->rChild);}}int _tmain(int argc, _TCHAR* argv[]){char* buff = (char*)malloc(100000);BinSearchTree T=NULL;fstream fIn("D:\\a.txt",ios::in);if (!fIn){cout<<"open a.txt fail"<<endl;return 0;}fIn.read(buff,100000);if(fIn.gcount() < 10){cout<<"read a.txt fail"<<endl;return 0;}fIn.close();string allData(buff);int iPre=0;while(1){ iPre = allData.find(";",iPre);if(-1 ==iPre)break;iPre++;insertNode(&T,allData.substr(iPre,10));}printTree(T);return 0;}


一直习惯用c的文件处理方式,,但是为了练下C++的方式,于是用fstream。。。结果写入的时候总是出问题,,最后只好又换成了C风格。⊙﹏⊙b汗

不过数据正确都处理了。反正程序结束就释放内存了,就没写删除结点的函数。


原创粉丝点击