提交 b8eb229f authored 作者: xuyang's avatar xuyang

init commit

上级
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**
out/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
.mvn
mvnw
mvnw.cmd
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
### VS Code ###
.vscode/
## Personal Projects and Coding Used by xuyang
#### **personal projects and coding used by xuyang**
##### *Package List:*
* snoflake 雪花算法
* sort 排序算法
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>projects</artifactId>
<groupId>com.xy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xy</groupId>
<artifactId>algorithm</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package algorithm.snowflake;
public class CircleArray {
//数组的最大容量
private int maxSize;
//front指向队列的第一个元素,也就是说arr[front]是队列的第一个元素
private int front;
//rear指向队列的最后一个元素的最后一个位置,初值为0
private int rear;
public int getFront() {
return front;
}
public int getRear() {
return rear;
}
//存放数据,模拟队列
private String[] arr;
public CircleArray(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new String[maxSize];
}
//判断是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//判断是否为空
public boolean isEmpty() {
return rear == front;
}
//添加数据到队列
public void addQueue(String n) {
//判断队列是否已满
if (isFull()) {
System.out.println("队列已满");
return;
}
//直接将数据加入
arr[rear] = n;
//将rear后移,必须考虑取模
rear = (rear + 1) % maxSize;
/*
这里手算了一下,实际取模就是想办法当rear和队列最大容量相等时,在加1就重新取到rear=1
有个通俗易懂的例子:跑步套圈
有一个环形跑道,假设,将环形跑道分割成10份。
front某时刻跑到第3格了,rear此时刻已经跑到第10格了。
那么rear继续往下跑的时候,会发现,跑的第“11格”(实际并不存在)其实就是第1格,是第二圈的第1格。
*/
}
//获取队列的中的数据
public String getQueue() {
//判断队列是否空
if (isEmpty()) {
//通过抛出异常来处理
throw new RuntimeException("队列为空,无法取出数据");
//throw可以直接return一个异常,不用再写return
}
//front指向队列的第一个元素
/*
1. 先把front对应的值保留到一个临时变量中
2. front后移,考虑取模
3. 将临时保存的变量返回
*/
String value = arr[front]; //先获取数据,front再后移
front = (front + 1) % maxSize;
return value;
}
//显示队列的所有数据
public void showQueue() {
//遍历数组
if (isEmpty()) {
System.out.println("队列为空,没有数据");
return;
}
//从front开始遍历,对需要遍历元素的个数进行计算。
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%s] = %s\n", i % maxSize, arr[i % maxSize]);
}
}
//有效数据的个数
public int size() {
return (rear + maxSize - front) % maxSize;
/*添加数据变的是rear,取出数据变的是front,所以当在第一个位置插入数据时,rear=2,front=1。
所以,如果不考虑取模,那有效数据个数就是rear-front
考虑取模的话会出现一种情况,rear已经开始“跑第二圈”了,front还在“第一圈”
*/
}
//显示队列头
public String headQueue() {
//判断是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空,没有数据");
}
return arr[front];
}
}
package algorithm.snowflake;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SnowflakeDemo {
//分割长度
private final long sequenceLength = 12L;
private final long workerIdLength = 10L;
private final long lastTimeStampLength = 41L;
//偏移量
private final long workerIdShift = sequenceLength;
private final long lastTimeStampShift = sequenceLength + workerIdLength;
//初始化
private long lastTimeStamp = -1L;
private long workerId = 0L;
private long sequence = 0L;
//掩码
private final long mark = ~(-1L << sequenceLength);
private static List<Long> resList = new ArrayList<>();
//请求总数
private final int loopNum = 100_000;
//请求总数
private final int clientTotal = 100_000;
//同时并发执行的线程数
private final int threadTotal = 200;
private SnowflakeDemo(){}
private SnowflakeDemo(long lastTimeStamp, long workerId, long sequence) {
this.lastTimeStamp = lastTimeStamp;
this.workerId = workerId;
this.sequence = sequence;
}
//生成ID
public synchronized String getId() {
long timeStamp = System.currentTimeMillis();
if(timeStamp < lastTimeStamp) {
throw new RuntimeException("time error");
}
if(timeStamp == lastTimeStamp) {
sequence = (sequence + 1) & mark;
if(sequence == 0) {
while(timeStamp <= lastTimeStamp) {
timeStamp = System.currentTimeMillis();
}
}
} else {
sequence = 0;
}
lastTimeStamp = timeStamp;
long res = sequence | (workerId << workerIdShift) | (timeStamp << lastTimeStampShift);
resList.add(res);
return Long.toBinaryString(res);
}
//单线程
public void m1() {
long bt = System.currentTimeMillis();
SnowflakeDemo snowflakeDemo = new SnowflakeDemo(bt, 0, 0);
for(int i = 0; i < loopNum; i++) {
//System.out.println(snowflakeDemo.getId());
snowflakeDemo.getId();
}
long et2 = System.currentTimeMillis();
System.out.println("耗时:"+(et2 - bt)+ "ms");
System.out.println("吞吐量为:"+loopNum*1.0/(et2 - bt)*1_000);
}
//模拟并发
public void m2() {
long bt = System.currentTimeMillis();
SnowflakeDemo snowflakeDemo = new SnowflakeDemo(bt, 0, 0);
ExecutorService executorService = Executors.newCachedThreadPool();
//信号量,此处用于控制并发的线程数
final Semaphore semaphore = new Semaphore(threadTotal);
//闭锁,可实现计数器递减
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
//执行此方法用于获取执行许可,当总计未释放的许可数不超过200时,
//允许通行,否则线程阻塞等待,直到获取到许可。
semaphore.acquire();
//System.out.println(Thread.currentThread().getName() + ": " + snowflakeDemo.getId());
snowflakeDemo.getId();
//释放许可
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
//闭锁减一
countDownLatch.countDown();
});
}
try {
countDownLatch.await();//线程阻塞,直到闭锁值为0时,阻塞才释放,继续往下执行
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdown();
long et2 = System.currentTimeMillis();
System.out.println("耗时:"+(et2 - bt)+ "ms");
System.out.println("吞吐量为:"+clientTotal*1.0/(et2 - bt)*1_000);
}
//环形数组
public void m3() {
long bt = System.currentTimeMillis();
int maxSize = 10_000;
SnowflakeDemo snowflakeDemo = new SnowflakeDemo(bt, 0, 0);
CircleArray circleArray = new CircleArray(maxSize);
while(!circleArray.isFull()) {
circleArray.addQueue(snowflakeDemo.getId());
}
for (int i = 0; i < loopNum; i++) {
circleArray.getQueue();
//System.out.println("头节点:" + circleArray.getFront() + ",尾节点:" + circleArray.getRear() + ",ID号:" + circleArray.getQueue());
if(circleArray.size() == maxSize/2) {
while(!circleArray.isFull()) {
circleArray.addQueue(snowflakeDemo.getId());
}
}
}
long et2 = System.currentTimeMillis();
System.out.println("耗时:"+(et2 - bt)+ "ms");
System.out.println("吞吐量为:"+loopNum*1.0/(et2 - bt)*1_000);
}
public void isIncrease(List<Long> list) {
int i = 0;
boolean flag = true;
while(i < list.size()-1) {
if(list.get(i) > list.get(i+1)) {
System.out.println("非单调递增ID:"+Long.toBinaryString(list.get(i)) + " > " + Long.toBinaryString(list.get(i+1)));
flag = false;
break;
}
i++;
}
if(flag) {
System.out.println("ID序列单调递增");
} else {
System.out.println("ID序列不是单调递增");
}
}
public void isSame(List<Long> list) {
int i = 0;
boolean flag = true;
list.sort(Long::compareTo);
while(i < list.size()-1) {
if(list.get(i).equals(list.get(i+1))) {
System.out.println("相同的序列为:"+Long.toBinaryString(list.get(i)));
flag = false;
break;
}
i++;
}
if(flag) {
System.out.println("ID序列没有重复");
} else {
System.out.println("ID序列有重复");
}
}
public static void main(String[] args) {
SnowflakeDemo snowflakeDemo = new SnowflakeDemo();
//======================使用单线程========================
//snowflakeDemo.m1();
//=======================================================
//======================使用多线程========================
//snowflakeDemo.m2();
//=======================================================
//======================使用RingBuffer===================
snowflakeDemo.m3();
//=======================================================
snowflakeDemo.isIncrease(resList);
snowflakeDemo.isSame(resList);
}
}
package algorithm.sort;
import java.util.Arrays;
public class QuickSort {
public static int[] quickSort(int[] arr, int start, int end){
int pivot = arr[start];
int i = start;
int j = end;
while(i < j){
while(i < j && arr[j] > pivot){
j--;
}
while(i < j && arr[i] < pivot){
i++;
}
if(arr[i] == arr[j] && i < j){
i++;
} else{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
if(i+1 < end){
arr = quickSort(arr, i+1, end);
}
if(i-1 > start){
arr = quickSort(arr, start, i-1);
}
return arr;
}
public static void main(String[] args) {
int[] arr = {10,22,97,25,35,11};
System.out.println(Arrays.toString(quickSort(arr, 0, arr.length-1)));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>projects</artifactId>
<groupId>com.xy</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.xy</groupId>
<artifactId>api</artifactId>
</project>
\ No newline at end of file
package api.array;
import java.util.Arrays;
/**
* Created by a on 2019/2/14.
*/
public class ArrayTest {
//字符串倒序及查找
void ArrayString() {
String A = "Helloworld";
char[] array = A.toCharArray();//字符串转化为数组
Arrays.sort(array); //排序 从小到大 大写在小写前
for (int i = array.length - 1; i >= 0; i--) { //倒序输出
System.out.print(array[i]);
}
int intIndex = A.indexOf("llo");
if (intIndex == -1) {
System.out.println("没有找到llo");
} else {
System.out.println("\n" + "llo的位置" + intIndex);
}
}
void StringBufferTest(){
StringBuffer A = new StringBuffer("helloworld");
A.append(" first test ");
A.append(5);
System.out.println("StringBuffer结果:"+A);
}
void BooleanTest(){
boolean A = true ;
String B = "123456";
char[] C = B.toCharArray();
for (int i = 0; i < C.length; i++) {
System.out.print(C[i]+" ");
A=false;
if(A)
break;
}
}
public static void main(String[] args) {
/*ArrayTest A = new ArrayTest();
A.ArrayString();
A.StringBufferTest();
A.BooleanTest();*/
double num = 5.09-0.08;
System.out.println(num);
}
}
package api.exception;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExceptionTest {
public static void test1() {
FileReader fileReader = null;
try {
fileReader = new FileReader("d:/a.txt");
int c1 = fileReader.read();
System.out.println(c1);
} catch (FileNotFoundException e) { //子类异常在父类异常前面
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fileReader!=null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static final List<String> list = new ArrayList<>();
public static String test2(String j){
int i = 1, s = 1, f = 1, a = 1, b = 1,c = 1,d = 1,e = 1;
list.add(new String("11111111111111111111111111111"));
return test2(s+i+f+a+b+c+d+e+"");
}
public static void main(String[] args) {
test2("123");
}
}
package api.io;
import java.io.*;
public class IoTest {
//InputStream
public static void getTextFile() {
FileInputStream fis = null;
try {
fis = new FileInputStream("d:/a.txt");
StringBuilder sb = new StringBuilder();
int temp = 0;
//获取文本中的内容
while((temp = fis.read())!= -1){
sb.append((char)temp);
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if(null != fis){
fis.close();//必须要关闭IO
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
//OutputStream
public static void writeTextFile() {
FileOutputStream fos = null;
String string = "今天去吃烤肉吧";
try {
fos = new FileOutputStream("d:/a.txt",true);//true表示会添加到内容后面,false表示会覆盖原内容
fos.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != fos) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//缓存字符流,复制TXT内容
public static void copyTextFile(String res,String dec){
FileReader fileReader = null;
FileWriter fileWriter = null;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
String temp = null;
try {
fileReader = new FileReader(res);
fileWriter = new FileWriter(dec);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
while((temp = bufferedReader.readLine())!=null){
bufferedWriter.write(temp);
bufferedWriter.newLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(bufferedWriter!=null)
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bufferedReader!=null)
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileWriter!=null)
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(fileReader!=null)
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void inputStreamReader(String res){
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(res),"UTF-8"));
StringBuilder A = new StringBuilder();
String B = null;
while((B = bufferedReader.readLine())!= null){
A.append(B);
}
System.out.println(A);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class IoTestMain{
public static void main(String[] args) {
//IoTest.getTextFile();
//IoTest.writeTextFile();
//IoTest.copyTextFile("D:/a.txt","D:/b.txt");
IoTest.inputStreamReader("D:/a.txt");
}
}
package api.iterator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IteratorTest {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
for(int i = 0; i < 10; i++){
list.add(i);
}
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
Integer num = iterator.next();
if(num == 0) {
iterator.remove();
}
}
System.out.println(list.toString());
}
}
package api.regex;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test1 {
public String regexReplace(String htmlStr) {
String localUrl2 = "http://www.xy.regex/";
String img = "";
Pattern p_image;
Matcher m_image;
Matcher m;
List<String> pics = new ArrayList<String>();
String regEx_img = "<a.*href\\s*=\\s*(.*?)[^>]*?>";
p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
m_image = p_image.matcher(htmlStr);
while (m_image.find()) {
img = img + "," + m_image.group();
m = Pattern.compile("href\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
while (m.find()) {
pics.add(m.group(1));
}
for (String i : pics) {
String regexp1 = ".*http://www.zhejiang.net/(.*)";
if (i.matches(regexp1)) {
Pattern p = Pattern.compile(regexp1);
Matcher matcher = p.matcher(i);
matcher.find();
String partName = matcher.group(1);
htmlStr = htmlStr.replaceFirst(i, localUrl2 + partName);
}
}
}
return htmlStr;
}
public static void main(String[] args) {
//String htmlStr = "<a href=\"http://www.zhejiang.net/图片测试(游).jpg\" />";
//String htmlStr = "<a href=\"http://www.zhejiang.net/图片测试(游).jpg\" />";
String htmlStr = "<a href=\"http://www.zhejiang.net/图片测试<游<><.jpg\" />";
Test1 test1 = new Test1();
System.out.println(test1.regexReplace(htmlStr));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xy</groupId>
<artifactId>projects</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>algorithm</module>
<module>api</module>
</modules>
</project>
\ No newline at end of file
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论