├── .gitignore ├── Articles ├── Interview │ └── AlwaysBeCoding.md └── README.md ├── Awk ├── Calendar │ └── calendar.awk ├── InterActiveStrReplace │ ├── .gitignore │ ├── InterActiveStrReplace.awk │ ├── dict │ └── str.dat ├── PersonInfo │ ├── PersonInfo.awk │ ├── family.dat │ ├── job.dat │ └── private.dat ├── README.md └── TextReplace │ ├── .gitignore │ ├── TextReplace.awk │ ├── dict │ └── text ├── C ├── Calculator │ ├── README.md │ └── main.c ├── DataStructureAndAlgorithm │ ├── dict_order │ │ ├── README.md │ │ └── dict_order.c │ ├── queue │ │ ├── README.md │ │ ├── main.c │ │ ├── makefile │ │ ├── my_animal.h │ │ ├── my_queue.c │ │ └── my_queue.h │ ├── skip_list │ │ ├── README.md │ │ └── skip_list.c │ └── stack │ │ ├── Makefile │ │ ├── README.md │ │ ├── main.c │ │ ├── myStack.c │ │ └── myStack.h ├── GetLineOperation │ ├── checkSyntaxError.c │ ├── deleteComments │ ├── deleteComments.c │ ├── foldLine │ ├── foldLine.c │ ├── getMaxLengthLine │ ├── getMaxLengthLine.c │ ├── getSpecifiedLengthLine │ └── getSpecifiedLengthLine.c ├── HomemadeOperatingSystem │ └── README.md ├── InterestingQuestion │ └── Queue │ │ └── DogAndCat │ │ └── main.c ├── PatQuestionBank │ ├── AdvancedLevel │ │ └── A1001.c │ ├── BasicLevel │ │ ├── B1001.c │ │ ├── B1002.c │ │ ├── B1003.c │ │ ├── B1004.c │ │ ├── B1005.c │ │ ├── B1006.c │ │ ├── B1007.c │ │ ├── B1008.c │ │ ├── B1009.c │ │ ├── B1010.c │ │ ├── B1011.c │ │ ├── B1012.c │ │ ├── B1013.c │ │ ├── B1014.c │ │ ├── B1015.c │ │ ├── B1016.c │ │ ├── B1017.c │ │ ├── B1018.c │ │ ├── B1019.c │ │ ├── B1020.c │ │ ├── B1021.c │ │ ├── B1022.c │ │ ├── B1023.c │ │ ├── B1024.c │ │ ├── B1025.c │ │ ├── B1026.c │ │ ├── B1027.c │ │ ├── B1086.c │ │ ├── B1087.c │ │ ├── B1088.c │ │ ├── B1089.c │ │ └── B1090.c │ ├── README.md │ └── TopLevel │ │ └── README.md ├── README.md ├── RedisSourceCodeDemo │ ├── README.md │ └── Sds │ │ ├── README.md │ │ ├── sds.c │ │ ├── test │ │ └── test.c └── SwapValue │ └── SwapValue.c ├── Css ├── .gitignore ├── Cake │ └── index.html ├── Dog │ ├── css │ │ └── styles.css │ ├── demo │ │ └── index.html │ └── index.html ├── Elephant │ ├── css │ │ └── styles.css │ └── index.html ├── FireWorks │ ├── demo.html │ └── index.html ├── Pig │ ├── css │ │ └── style.css │ ├── demo │ │ └── index.html │ └── index.html ├── Snow │ ├── demo.html │ └── pics │ │ ├── snow-b.png │ │ ├── snow-f.png │ │ └── snow-m.png ├── Test │ └── index.html └── TimeLine │ └── index.html ├── Go ├── GoLearn.md ├── Image2Base64 │ ├── README.md │ ├── go.mod │ ├── go.sum │ └── main.go ├── LearnDemo │ └── PrintBigDigits │ │ ├── PrintBigDigits.go │ │ └── README.md ├── README.md └── Timer │ └── Timer.go ├── JavaScript ├── Demo │ ├── DemoOne │ │ ├── changeValue.html │ │ └── validateInputValue.html │ └── DemoTwo │ │ └── Demo.html ├── README.md ├── TencentMapApi │ └── TencentMapApi.html └── Tools │ ├── Assets │ ├── phpSerializer.js │ └── utf.js │ ├── IMEIBuilder │ └── index.html │ ├── Serialization │ └── index.html │ ├── Unserialization │ └── index.html │ └── index.html ├── LICENSE ├── LearnPlan.md ├── Php ├── .gitignore ├── AttributesChangeLog │ └── AttributesChangeLog.php ├── BloomFilter │ └── BloomFilter.php ├── Container │ ├── ContextualBindingBuilder.php │ ├── ContextualBindingBuilderInterface.php │ ├── Examples │ │ ├── ContainerEvent.php │ │ ├── ContextBind.php │ │ ├── ExtendBind.php │ │ ├── ImplementToInterface.php │ │ ├── InitalDataBind.php │ │ ├── InstanceBind.php │ │ ├── SimpleBind.php │ │ ├── SingletonBind.php │ │ └── TagBind.php │ ├── OContainer.php │ ├── OContainerInterface.php │ └── README.md ├── DataStructureAndAlgorithm │ ├── BPlusTree │ │ └── BPlusTree.php │ ├── BTree │ │ └── BTree.php │ ├── Hash │ │ └── HashToImplementArray.php │ ├── Heap │ │ ├── MaxHeap.php │ │ └── MinHeap.php │ ├── PageRank │ │ └── PageRank.php │ ├── README.md │ ├── RedBlackTree │ │ ├── README.md │ │ └── RedBlackTree.php │ ├── SkipList │ │ └── SkipList.php │ └── Sort │ │ ├── CompareSort │ │ ├── InsertSort │ │ │ ├── InsertSort.php │ │ │ └── ShellSort.php │ │ ├── MergeSort │ │ │ └── MergeSort.php │ │ ├── SelectSort │ │ │ ├── HeapSort.php │ │ │ └── SimpleSelectSort.php │ │ └── SwapSort │ │ │ ├── BubbleSort.php │ │ │ └── QuickSort.php │ │ └── NoCompareSort │ │ ├── BucketSort.php │ │ ├── CountSort.php │ │ └── RadixSort.php ├── DesignPatterns │ ├── Adapter │ │ └── Adapter.php │ ├── Command │ │ └── Command.php │ ├── Composite │ │ └── Composite.php │ ├── Decorator │ │ └── Decorator.php │ ├── Facade │ │ └── Facade.php │ ├── Factory │ │ ├── AbstractFactory.php │ │ ├── FactoryMethod.php │ │ └── SimpleFactory.php │ ├── Iterator │ │ └── Iterator.php │ ├── Observer │ │ ├── pullObserver.php │ │ └── pushObserver.php │ ├── Pipeline │ │ └── Pipeline.php │ ├── Proxy │ │ └── Proxy.php │ ├── README.md │ ├── Singleton │ │ ├── Singleton.php │ │ └── StrictSingleton.php │ ├── State │ │ └── State.php │ ├── Strategy │ │ ├── hasSetter.php │ │ └── noSetter.php │ └── TemplateMethod │ │ └── TemplateMethod.php ├── FakeApi │ ├── .gitignore │ ├── Log.php │ └── MyParts │ │ ├── MyParts.php │ │ └── index.php ├── FileOperation │ ├── DirTranverse │ │ └── DirTranverse.php │ ├── ExcelColIncrease │ │ └── ExcelColIncrease.php │ ├── GenerateBigFile │ │ └── GenerageBigFile.php │ └── README.md ├── FilterSensitiveWord │ ├── FilterSensitiveWord.php │ ├── FilterSensitiveWord_2.php │ └── README.md ├── HyperLogLog │ ├── Bucket.php │ ├── HyperLogLog.php │ ├── README.md │ └── Test.php ├── InterestingQuestion │ └── Stack │ │ ├── ImplementQueueWithTwoStack │ │ ├── Queue.php │ │ ├── QueueExample.php │ │ └── README.md │ │ ├── StackReverse │ │ ├── README.md │ │ ├── ReverseStack.php │ │ └── ReverseStackExample.php │ │ └── StackWithGetMin │ │ ├── AbstractMyStack.php │ │ ├── MyStack.php │ │ ├── MyStackAnother.php │ │ ├── MyStackAnotherExample.php │ │ ├── MyStackExample.php │ │ └── README.md ├── LaravelTest │ ├── MiddleWare │ │ └── MiddleWare.php │ └── README.md ├── LogManagementSystem │ └── README.md ├── PhpSyntaxTestCode │ ├── ArrayReduce.php │ ├── CloneSyntax.php │ ├── FileOperation.php │ ├── GetFileLastNumRow.php │ ├── README.md │ ├── TestData │ │ ├── FileOperation │ │ │ ├── testA _original.txt │ │ │ ├── testA.txt │ │ │ ├── testB.txt │ │ │ └── testB_original.txt │ │ └── GetFileLastNumRow │ │ │ └── test.data │ └── ThrowableTest │ │ └── ThrowableTest.php ├── README.md ├── ReplaceStrTemplate │ └── ReplaceStrTemplate.php ├── SimpleContainer │ ├── README.md │ ├── SimpleContainer.php │ └── Usage.php ├── SimpleDataBase │ ├── DataBaseObject.php │ ├── MyDataBase.php │ ├── README.md │ ├── data │ │ └── dbTest.dat │ └── index │ │ └── dbTest.inx ├── SimpleRandom │ ├── App │ │ ├── AbstractApp.php │ │ └── Welcome.php │ ├── Http │ │ ├── Request.php │ │ └── Response.php │ ├── Service │ │ ├── Dispatch.php │ │ └── Random.php │ ├── Tools │ │ ├── ObjectSet.php │ │ └── StrTool.php │ ├── autoload.php │ └── index.php ├── Sudoku │ └── Sudoku.php ├── Tests │ ├── BaseTestCase.php │ ├── InterestingQuestion │ │ └── Stack │ │ │ ├── ImplementQueueWithTwoStack │ │ │ └── QueueTest.php │ │ │ ├── StackReverse │ │ │ └── StackReverseTest.php │ │ │ └── StackWithGetMin │ │ │ ├── MyStackAnotherTest.php │ │ │ └── MyStackTest.php │ └── bootstrap.php ├── Toml │ └── Array2Toml.php ├── TransformDataPieces │ └── TransformDataPieces.php ├── UrlShortener │ ├── AutoIncreaseShortener.php │ ├── Md5Shortener.php │ └── README.md ├── UsefulTools │ ├── ListFilesAndDirectories │ │ ├── List.php │ │ └── README.md │ ├── README.md │ └── TransformStringToKeyValueArray │ │ ├── README.md │ │ └── Transform.php └── phpunit.xml ├── README.md ├── ResourceCollection └── Resource.md ├── Shell ├── AutoConfigLnmpWebSite │ └── AutoConfigLnmpWebSite.sh └── README.md ├── composer.json └── composer.lock /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | /nbproject 3 | .DS_Store -------------------------------------------------------------------------------- /Articles/README.md: -------------------------------------------------------------------------------- 1 | #### 一些有趣的文章,摘到这里供大家欣赏~~~ 2 | #### 文章开头会注明出处,如有版权问题请联系liu546hao@163.com. -------------------------------------------------------------------------------- /Awk/Calendar/calendar.awk: -------------------------------------------------------------------------------- 1 | # 在shell中生成日历 2 | # 使用方式 3 | # awk -f thisFile +2017 4 | # awk -f thisFile +2017.10 5 | # awk -f thisFile +2017.10.10 6 | # 7 | function whichWeek(y, m, d, s) { 8 | s = 0 9 | if (((y%4 == 0) && (y%100 != 0)) || (y%400 == 0)) if (M[2] == 28) M[2]++ 10 | if (y>0) s += --y + int(y/4) - int(y/100) + int(y/400) 11 | while (m > 1) s += M[--m] 12 | return (s+d)%7 13 | } 14 | 15 | function printCalendar(y, m, d, nowWeek, i){ 16 | printf("%d%s %d%s\n", y, "年", m, "月") 17 | print "日 一 二 三 四 五 六 " 18 | printf("%s", repeat(" ", ((nowWeek+1)%7)*3)) 19 | for (i=1; i<=M[m]; i++) { 20 | if ((nowWeek+i) % 7 != 6) { 21 | printf("%2d ", i) 22 | } else { 23 | printf("%2d \n", i) 24 | } 25 | } 26 | print "\n" 27 | } 28 | function repeat(flag, time, i, str){ 29 | for (i=0; i 1 && ARGV[1] ~ /^\+.*$/) { 37 | print ARGC, ARGV[1] 38 | opt = substr(ARGV[1], 2) 39 | delete ARGV[1] 40 | } 41 | return opt 42 | } 43 | BEGIN { 44 | M[1] = 31 45 | M[2] = 28 46 | M[3] = 31 47 | M[4] = 30 48 | M[5] = 31 49 | M[6] = 30 50 | M[7] = 31 51 | M[8] = 31 52 | M[9] = 30 53 | M[10] = 31 54 | M[11] = 30 55 | M[12] = 31 56 | W[0] = "日" 57 | W[1] = "一" 58 | W[2] = "二" 59 | W[3] = "三" 60 | W[4] = "四" 61 | W[5] = "五" 62 | W[6] = "六" 63 | split(option(), date, ".") 64 | nowWeek = whichWeek(date[1]+0, date[2]+0, date[3]+0) 65 | if (date[3] != "") { 66 | print "星期" W[nowWeek] 67 | } else if (date[2] != "") { 68 | printCalendar(date[1]+0, date[2]+0, M[date[2]], nowWeek) 69 | } else { 70 | for (j=1; j<=12; j++) { 71 | printCalendar(date[1]+0, j, M[i], whichWeek(date[1]+0, j, 0)) 72 | } 73 | } 74 | } -------------------------------------------------------------------------------- /Awk/InterActiveStrReplace/.gitignore: -------------------------------------------------------------------------------- 1 | replace.out -------------------------------------------------------------------------------- /Awk/InterActiveStrReplace/InterActiveStrReplace.awk: -------------------------------------------------------------------------------- 1 | # str.dat中的字符串,按字典dict中指定的替换内容,进行交互式替换 2 | # Y-替换 3 | # A-替换当前及之后出现的行 4 | # I-不替换,之后出现的也不替换 5 | # 其它-不替换 6 | # 使用: awk -f InterActiveStrReplace.awk str.dat 7 | 8 | BEGIN { 9 | i = 0; 10 | while (getline < "dict" > 0) { 11 | source[i] = $1; 12 | destination[i] = $2; 13 | i++; 14 | } 15 | } 16 | { 17 | for (i in source) { 18 | if (i in all) { 19 | gsub(source[i], destination[i], $0); 20 | continue; 21 | } 22 | head = "" 23 | tail = $0; 24 | while (idx = index(tail, source[i])) { 25 | tbuf = tail; 26 | sub(source[i], "\033[41m&\033[0m", tbuf); 27 | printf("%4d : %s%s\n", NR, head, tbuf); 28 | printf("[%s] -> [%s] (Yes/No/All/Ignore): ", source[i], destination[i]); 29 | getline q < "/dev/stdin"; 30 | if (q ~ /^[yY]/) { 31 | sub(source[i], destination[i], tail); 32 | head = head substr(tail, 1, idx+length(destination[i])); 33 | tail = substr(tail, idx+length(destination[i])+1); 34 | } else if (q ~ /^[aA]/) { 35 | gsub(source[i], destination[i], tail); 36 | all[i] = source[i]; 37 | break; 38 | } else if (q ~ /^[iI]/) { 39 | delete source[i]; 40 | break; 41 | } else { 42 | head = head substr(tail, 1, idx + length(source[i])); 43 | tail = substr(tail, idx + length(source[i]) + 1); 44 | } 45 | } 46 | $0 = head tail; 47 | } 48 | print $0 > "replace.out"; 49 | } -------------------------------------------------------------------------------- /Awk/InterActiveStrReplace/dict: -------------------------------------------------------------------------------- 1 | hello hi 2 | dog cat 3 | rain water 4 | -------------------------------------------------------------------------------- /Awk/InterActiveStrReplace/str.dat: -------------------------------------------------------------------------------- 1 | there is rain. 2 | dog is eating. 3 | ok hello world! 4 | -------------------------------------------------------------------------------- /Awk/PersonInfo/PersonInfo.awk: -------------------------------------------------------------------------------- 1 | # 模拟数据库查询某人的详细信息: 2 | # private.dat 存放个人简略信息 3 | # job.dat 存放工作相关信息 4 | # family.dat 存放家庭信息 5 | # 6 | # 使用方式: awk -f PersonInfo.awk +姓名 private.dat 7 | # 例如: awk -f PersonInfo.awk +阿部慎平 private.dat 8 | # 输出要查询人的详细信息 9 | 10 | BEGIN { 11 | FS = "[\t]+"; 12 | name = option(); 13 | } 14 | $2 == name{ 15 | printf("%s : %s\n", "姓名", $2); 16 | printf("%s : %s\n", "住址", $4); 17 | printf("%s : %s\n", "电话", $3); 18 | job = $5; 19 | id = $1; 20 | printJob(job); 21 | printFamily(id); 22 | printf("%s\n", repeat("---", 8)); 23 | } 24 | function option(opt) { 25 | if ((ARGC > 1)&&(ARGV[1] ~ /^+.*$/)) { 26 | opt = substr(ARGV[1], 2); 27 | delete ARGV[1]; 28 | } 29 | return opt; 30 | } 31 | function printJob(job, n) { 32 | n = 0; 33 | while (getline < "job.dat" > 0) { 34 | if ($1 == job) { 35 | printf("公司:%s 职位:%s 电话:%s\n", $1, $2, $3); 36 | n++; 37 | } 38 | } 39 | if (n == 0) { 40 | print "无\n"; 41 | } 42 | } 43 | function printFamily(id, n) { 44 | print "家庭关系\n"; 45 | n = 0; 46 | while (getline < "family.dat" > 0) { 47 | if ($1 == id) { 48 | printf("关系:%s 姓名:%s\n", $3, $2); 49 | n++; 50 | } 51 | } 52 | if (n == 0) { 53 | print "无\n"; 54 | } 55 | } 56 | function repeat(flag, time, i, str) { 57 | for (i=0; i 0) { 5 | s[i] = $1; 6 | d[i] = $2; 7 | i++; 8 | } 9 | } 10 | { 11 | for (i in s) { 12 | } 13 | } -------------------------------------------------------------------------------- /Awk/TextReplace/dict: -------------------------------------------------------------------------------- 1 | happy|very nice 2 | good|moon 3 | morning|evening 4 | warm|cool -------------------------------------------------------------------------------- /Awk/TextReplace/text: -------------------------------------------------------------------------------- 1 | good|hi|good 2 | happy|hello|happy -------------------------------------------------------------------------------- /C/Calculator/README.md: -------------------------------------------------------------------------------- 1 | # calculator 2 | c语言计算器 3 | -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/dict_order/README.md: -------------------------------------------------------------------------------- 1 | ### 问题 2 | 给定一个正整数,实现一个方法来求出离该整数最近的大于自身的“换位数”. 3 | 例如 : 4 | 12345 -> 12354 5 | 12354 -> 12435 6 | 12435 -> 12453 7 | 8 | ### 实现思路 9 | 以12354为例 10 | 1.寻找最大逆序 11 | 最大逆序为 54 12 | 13 | 2.逆序的前一个和逆序中刚好大于它的值互换 14 | 逆序的前一个值是3,逆序中刚好大于它的值是4,这两个值互换 15 | 16 | 3.逆序重排为顺序 17 | 当前逆序为53,重排为顺序则为35 18 | 结果为12435 19 | -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/dict_order/dict_order.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /* 5 | * 给定一个正整数,实现一个方法来求出离该整数最近的大于自身的“换位数”. 6 | * 例如 12345 -> 12354 7 | * 12354 -> 12435 12435->12453 8 | */ 9 | 10 | #define NUMBER_MAX_DIGITS 10 11 | 12 | int main(void) { 13 | char c, tmp; 14 | char num[NUMBER_MAX_DIGITS]; 15 | int cLength = 0, i, j, rLocation, bigLoc; 16 | 17 | while ((c = getchar()) != '\n') { 18 | num[cLength++] = c; 19 | } 20 | 21 | //1.寻找最大逆序 22 | rLocation = cLength - 1; 23 | for (i = cLength - 1; i > 0; i--) { 24 | if (num[i-1] > num[i]) { 25 | rLocation = i - 1; 26 | } else { 27 | break; 28 | } 29 | } 30 | //2.逆序的前一个和逆序中刚好大于它的值互换 31 | bigLoc = rLocation; 32 | for (i = rLocation; i < cLength; i++) { 33 | if (num[i] > num[rLocation - 1] && num[i] < num[bigLoc]) { 34 | bigLoc = i; 35 | } 36 | } 37 | 38 | tmp = num[rLocation - 1]; 39 | num[rLocation - 1] = num[bigLoc]; 40 | num[bigLoc] = tmp; 41 | 42 | printf("%s\n", num); 43 | 44 | //3.逆序重排为顺序 45 | 46 | for (i = rLocation; i < cLength; i++) { 47 | for (j = rLocation; j < cLength - 1 - i + rLocation; j++) { 48 | if (num[j] > num[j+1]) { 49 | tmp = num[j]; 50 | num[j] = num[j+1]; 51 | num[j+1] = tmp; 52 | } 53 | } 54 | } 55 | printf("%s\n", num); 56 | 57 | } -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/README.md: -------------------------------------------------------------------------------- 1 | #### 队列Queue简单实现 2 | 3 | ##### 环境: Linux 4 | ##### 编译: make 5 | ##### 执行: ./main 6 | ##### 清除编译结果: make clean -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "my_queue.h" 7 | 8 | 9 | 10 | int main() { 11 | MyAnimal *a; 12 | MyAnimal *b; 13 | 14 | MyQueue *queue; 15 | 16 | a = malloc(sizeof(struct MyAnimal)); 17 | b = malloc(sizeof(struct MyAnimal)); 18 | 19 | a->type = 1; 20 | a->name = "cat"; 21 | 22 | b->type = 2; 23 | b->name = "dog"; 24 | 25 | queue = createNewQueue(); 26 | 27 | if (queue == NULL) { 28 | return EXIT_FAILURE; 29 | } 30 | 31 | enQueue(queue, a); 32 | enQueue(queue, b); 33 | 34 | MyAnimal *myHeadValue = (MyAnimal *)(deQueue(queue)); 35 | 36 | 37 | printf("%d : %s\n", myHeadValue->type, myHeadValue->name); 38 | 39 | destroyQueue(queue); 40 | 41 | return EXIT_SUCCESS; 42 | } -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/makefile: -------------------------------------------------------------------------------- 1 | main : main.o myQueue.o 2 | $(CC) -o main main.o myQueue.o $(CFLAGS) 3 | 4 | main.o : main.c myQueue.h 5 | $(CC) -c main.c 6 | 7 | myQueue.o : myQueue.c myQueue.h 8 | $(CC) -c myQueue.c 9 | 10 | .PHONY : clean 11 | 12 | clean : 13 | rm *.o main -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/my_animal.h: -------------------------------------------------------------------------------- 1 | typedef struct MyAnimal { 2 | int type; 3 | char *name; 4 | } MyAnimal; -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/my_queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "my_queue.h" 3 | 4 | myQueue *createNewQueue() { 5 | MyQueue *queue = NULL; 6 | queue = (MyQueue *)malloc(sizeof(struct MyQueue)); 7 | queue->head = 0; 8 | queue->tail = 0; 9 | } 10 | 11 | bool isEmpty(MyQueue *queue) { 12 | if (queue == NULL) { 13 | return true; 14 | } 15 | if ((queue->head == 0) && (queue->tail == 0)) { 16 | return true; 17 | } 18 | 19 | return false; 20 | } 21 | 22 | void enQueue(MyQueue *queue, void *data) { 23 | QNode *newNode = NULL; 24 | 25 | if (queue == NULL) { 26 | return; 27 | } 28 | newNode = (QNode *)malloc(sizeof(struct QNode)); 29 | 30 | if (newNode == NULL) { 31 | return; 32 | } 33 | 34 | newNode->value = data; 35 | 36 | if ((queue->head == 0) && (queue->tail == 0)) { 37 | queue->head = newNode; 38 | queue->tail = newNode; 39 | newNode->next = 0; 40 | newNode->prev = 0; 41 | } else { 42 | newNode->next = queue->tail->next; 43 | newNode->prev = queue->tail; 44 | queue->tail = newNode; 45 | } 46 | } 47 | 48 | void *deQueue(MyQueue *queue) { 49 | if (queue == NULL) { 50 | return NULL; 51 | } 52 | if (isEmpty(queue)) { 53 | return NULL; 54 | } 55 | void *value = queue->head->value; 56 | 57 | QNode *tmp = queue->head; 58 | 59 | queue->head = queue->head->next; 60 | if (queue->head != 0) { 61 | queue->head->prev = 0; 62 | } 63 | 64 | free(tmp); 65 | return value; 66 | } 67 | 68 | void destroyQueue(MyQueue *queue) { 69 | QNode *tmp = queue->head; 70 | QNode *now = queue->head; 71 | 72 | while(now) { 73 | tmp = now; 74 | now = now->next; 75 | free(tmp); 76 | } 77 | 78 | free(queue); 79 | } -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/queue/my_queue.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include "my_animal.h" 3 | 4 | typedef struct QNode { 5 | void *value; 6 | struct QNode *prev; 7 | struct QNode *next; 8 | } QNode; 9 | 10 | typedef struct MyQueue{ 11 | struct QNode *head; 12 | struct QNode *tail; 13 | } MyQueue; 14 | 15 | MyQueue *createNewQueue(); 16 | 17 | bool isEmpty(MyQueue *queue); 18 | 19 | void enQueue(MyQueue *queue, void *data); 20 | 21 | void *deQueue(MyQueue *queue); 22 | 23 | void destroyQueue(MyQueue *queue); -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/skip_list/README.md: -------------------------------------------------------------------------------- 1 | #### 跳跃表实现 -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/stack/Makefile: -------------------------------------------------------------------------------- 1 | main : main.o myStack.o 2 | $(CC) -o main main.o myStack.o $(CFLAGS) 3 | 4 | myStack.o : myStack.c 5 | $(CC) -c myStack.c $(CFLAGS) 6 | 7 | .PHONY : clean 8 | 9 | clean: 10 | rm -rf *.o main -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/stack/README.md: -------------------------------------------------------------------------------- 1 | #### 栈Stack简单实现 2 | 3 | ##### 环境: Linux 4 | ##### 编译: make 5 | ##### 执行: ./main 6 | ##### 清除编译结果: make clean 7 | -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/stack/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "myStack.h" 4 | 5 | 6 | void main () { 7 | myStack *ms = NULL; 8 | 9 | ms = createMyStack(); 10 | 11 | myPush(ms, 1); 12 | myPush(ms, 2); 13 | myPush(ms, 3); 14 | 15 | while(!isEmpty(ms)) { 16 | printf("---%d\n", myPop(ms)); 17 | } 18 | 19 | destroyMyStack(ms); 20 | } -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/stack/myStack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "myStack.h" 3 | 4 | myStack *createMyStack() { 5 | myStack *ms = malloc(sizeof(struct myStack)); 6 | 7 | if (ms == NULL) { 8 | return NULL; 9 | } 10 | 11 | ms->top = 0; 12 | 13 | return ms; 14 | } 15 | 16 | void myPush(myStack *ms, int value) { 17 | sNode *n = malloc(sizeof(struct sNode)); 18 | if (n == NULL) { 19 | return; 20 | } 21 | 22 | n->value = value; 23 | 24 | if (isEmpty(ms)) { 25 | n->prev = 0; 26 | } else { 27 | n->prev = ms->top; 28 | } 29 | 30 | ms->top = n; 31 | } 32 | 33 | int myPop(myStack *ms) { 34 | if (!isEmpty(ms)) { 35 | int value = ms->top->value; 36 | sNode *tmp = ms->top; 37 | ms->top = ms->top->prev; 38 | free(tmp); 39 | return value; 40 | } else { 41 | return -1; 42 | } 43 | } 44 | 45 | int isEmpty(myStack *ms) { 46 | return ms->top == 0; 47 | } 48 | 49 | void destroyMyStack(myStack *ms) { 50 | sNode *tmp = ms->top; 51 | sNode *current = ms->top; 52 | while(current) { 53 | tmp = current; 54 | current = current->prev; 55 | free(tmp); 56 | } 57 | free(ms); 58 | } -------------------------------------------------------------------------------- /C/DataStructureAndAlgorithm/stack/myStack.h: -------------------------------------------------------------------------------- 1 | typedef struct sNode { 2 | struct sNode *prev; 3 | int value; 4 | } sNode; 5 | 6 | typedef struct myStack { 7 | sNode *top; 8 | } myStack; 9 | 10 | myStack *createMyStack(); 11 | 12 | void myPush(myStack *ms, int value); 13 | 14 | int myPop(myStack *ms); 15 | 16 | int isEmpty(myStack *ms); 17 | 18 | void destroyMyStack(myStack *ms); 19 | -------------------------------------------------------------------------------- /C/GetLineOperation/checkSyntaxError.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 编写一个程序,查找C语言程序中的基本语法错误,如圆括号 3 | * ,方括号,花括号不配对等。要正确处理引号(包括单引号和 4 | * 双引号),转义字符序列与注释。(如果读者想把该程序写成 5 | * 完全通用的程序,难度会比较大) 6 | * 7 | * 8 | */ 9 | 10 | #include 11 | 12 | void main () 13 | { 14 | 15 | } -------------------------------------------------------------------------------- /C/GetLineOperation/deleteComments: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/C/GetLineOperation/deleteComments -------------------------------------------------------------------------------- /C/GetLineOperation/deleteComments.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 编写一个删除C语言程序中所有的注释语句。要正确处理 3 | * 带引号的字符串与字符常量。在C语言中,注释不允许嵌套。 4 | * 5 | * 6 | * 7 | */ 8 | 9 | #include 10 | #include 11 | 12 | void main () 13 | { 14 | printf("%d", INT_MAX); 15 | } 16 | 17 | -------------------------------------------------------------------------------- /C/GetLineOperation/foldLine: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/C/GetLineOperation/foldLine -------------------------------------------------------------------------------- /C/GetLineOperation/foldLine.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 编写一个程序,把较长的输入行“折”成短一些的两行或多行 4 | * 折行的位置在输入行的第n列之前的最后一个非空格之后。要保证 5 | * 程序能够智能地处理输入行很长以及在指定的列前没有空格或制表 6 | * 符时的情况 7 | * 8 | * 题中的第n列之前的最后一个非空格之后,该程序没有满足,只满足第n列之前最后一个字符之后。 9 | */ 10 | 11 | #include 12 | 13 | #define MAX_LINE_LENGTH 100 14 | #define MAX_LINE_NUMBER 10 15 | 16 | 17 | 18 | 19 | int myGetLine(char resStr[][MAX_LINE_LENGTH], int n, int limit); 20 | 21 | void main () 22 | { 23 | char myStr[MAX_LINE_LENGTH]; 24 | char resStr[MAX_LINE_NUMBER][MAX_LINE_LENGTH]; 25 | 26 | int lineCnt, j = 0; 27 | int n = 4; 28 | 29 | while ((lineCnt = myGetLine(resStr, n, MAX_LINE_LENGTH)) > 0) { 30 | for (int i = 0; i <= lineCnt; i++) { 31 | j = 0; 32 | while (resStr[i][j] != '\0') { 33 | putchar(resStr[i][j]); 34 | j++; 35 | } 36 | } 37 | } 38 | } 39 | 40 | int myGetLine(char resStr[][MAX_LINE_LENGTH], int n, int limit) 41 | { 42 | int c; 43 | int cnt = 0; 44 | int lineCnt = 0; 45 | 46 | while (((c = getchar()) != EOF) && (c != '\n') && (cnt < (limit - 1))) { 47 | resStr[lineCnt][cnt] = c; 48 | 49 | if (cnt >= (n - 2)) { 50 | cnt++; 51 | resStr[lineCnt][cnt] = '\n'; 52 | cnt++; 53 | resStr[lineCnt][cnt] = '\0'; 54 | cnt = 0; 55 | lineCnt++; 56 | } else { 57 | cnt++; 58 | } 59 | } 60 | 61 | if (c == '\n') { 62 | resStr[lineCnt][cnt] = '\n'; 63 | cnt++; 64 | } 65 | 66 | resStr[lineCnt][cnt] = '\0'; 67 | 68 | return lineCnt; 69 | } -------------------------------------------------------------------------------- /C/GetLineOperation/getMaxLengthLine: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/C/GetLineOperation/getMaxLengthLine -------------------------------------------------------------------------------- /C/GetLineOperation/getMaxLengthLine.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX_LINE_LENGTH 1000 4 | 5 | /* 6 | * 7 | * linux下,使用ctrl + D结束输入 8 | * 9 | * 显示最大长度的输入行。 10 | * 11 | */ 12 | 13 | int mygetline(char str[], int limit); 14 | void mycopy(char fromStr[], char toStr[], int limit); 15 | 16 | 17 | void main () 18 | { 19 | char mystr[MAX_LINE_LENGTH]; 20 | char toStr[MAX_LINE_LENGTH]; 21 | 22 | int max = 0; 23 | int len = 0; 24 | 25 | while ((len = mygetline(mystr, MAX_LINE_LENGTH)) > 0) { 26 | if (max < len) { 27 | max = len; 28 | mycopy(mystr, toStr, MAX_LINE_LENGTH); 29 | } 30 | } 31 | printf("\n Max Length Line is : %s\n", toStr); 32 | 33 | } 34 | 35 | int mygetline(char mystr[], int limit) 36 | { 37 | int c; 38 | int lineCount = 0; 39 | 40 | while (((c = getchar()) != EOF) && (c != '\n') && (lineCount < (limit - 1))) { 41 | mystr[lineCount] = c; 42 | lineCount++; 43 | } 44 | 45 | if (lineCount == (limit - 1)) { 46 | while (((c = getchar()) != EOF) && (c != '\n')); 47 | } 48 | if (c == '\n') { 49 | mystr[lineCount] = '\n'; 50 | lineCount++; 51 | } 52 | 53 | mystr[lineCount] = '\0'; 54 | 55 | return lineCount; 56 | } 57 | 58 | void mycopy(char fromStr[], char toStr[], int limit) 59 | { 60 | int i = 0; 61 | int c; 62 | 63 | while ((c = fromStr[i]) != '\0') { 64 | toStr[i] = c; 65 | i++; 66 | } 67 | 68 | toStr[i] = '\0'; 69 | } -------------------------------------------------------------------------------- /C/GetLineOperation/getSpecifiedLengthLine: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/C/GetLineOperation/getSpecifiedLengthLine -------------------------------------------------------------------------------- /C/GetLineOperation/getSpecifiedLengthLine.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * 获取任意长度的输入行 4 | * 5 | * 6 | * 7 | * 8 | */ 9 | 10 | #include 11 | 12 | 13 | #define MAX_LINE_LENGTH 1000 14 | #define MAX_LINE_NUMBER 100 15 | 16 | int myGetLine(char myStr[], int lengthLimit); 17 | void myCopy(char fromStr[], char toStr[]); 18 | 19 | void main (int argc, char **argv) 20 | { 21 | int speLength = 0; 22 | int curLen = 0; 23 | int sumLen = 0; 24 | 25 | char myStr[MAX_LINE_LENGTH]; 26 | char resStr[MAX_LINE_NUMBER][MAX_LINE_LENGTH]; 27 | 28 | if (argc > 1) { 29 | speLength = argv[1][0] - '0'; 30 | } 31 | 32 | while ((curLen = myGetLine(myStr, MAX_LINE_LENGTH)) > 0) { 33 | 34 | if (curLen == (speLength + 1)) { 35 | myCopy(myStr, resStr[sumLen]); 36 | sumLen++; 37 | } 38 | } 39 | 40 | printf("\nLength %d Strings:\n", speLength); 41 | 42 | for (int i = 0; i < sumLen; i++) { 43 | printf("\t(%d) : %s", i+1, resStr[i]); 44 | } 45 | } 46 | 47 | int myGetLine (char myStr[], int lengthLimit) 48 | { 49 | int c; 50 | int countNum = 0; 51 | 52 | while (((c = getchar()) != EOF) && (c != '\n') && (countNum < (lengthLimit - 1))) { 53 | myStr[countNum] = c; 54 | countNum++; 55 | } 56 | 57 | if (countNum >= (lengthLimit - 1)) { 58 | while (((c = getchar()) != EOF) && (c != '\n')); 59 | } 60 | 61 | if (c == '\n') { 62 | myStr[countNum] = c; 63 | countNum++; 64 | } 65 | 66 | myStr[countNum] = '\0'; 67 | 68 | return countNum; 69 | } 70 | 71 | void myCopy(char fromStr[], char toStr[]) 72 | { 73 | int c; 74 | int offset = 0; 75 | 76 | while ((c = fromStr[offset]) != '\0') { 77 | toStr[offset] = c; 78 | offset++; 79 | } 80 | 81 | toStr[offset] = '\0'; 82 | } -------------------------------------------------------------------------------- /C/HomemadeOperatingSystem/README.md: -------------------------------------------------------------------------------- 1 | #### 学习《30天自制操作系统》 -------------------------------------------------------------------------------- /C/InterestingQuestion/Queue/DogAndCat/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | /* 4 | * 猫狗问题 5 | * 6 | * 7 | * 8 | */ 9 | int main () { 10 | printf("Hello"); 11 | return EXIT_SUCCESS; 12 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/AdvancedLevel/A1001.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1001 A+B Format(20 分) 3 | 4 | Calculate a+b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). 5 | Input Specification: 6 | 7 | Each input file contains one test case. Each case contains a pair of integers a and b where −10​6​​≤a,b≤10​6​​. The numbers are separated by a space. 8 | Output Specification: 9 | 10 | For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format. 11 | Sample Input: 12 | 13 | -1000000 9 14 | 15 | Sample Output: 16 | 17 | -999,991 18 | 19 | */ 20 | 21 | #include 22 | #include 23 | #include 24 | 25 | int main () 26 | { 27 | int a, b, i, cnt = 0, cc = 0; 28 | int sum, str_len; 29 | int flag = 0; 30 | char s[20], c[20]; 31 | 32 | if (!scanf("%d %d", &a, &b)) { 33 | return 1; 34 | } 35 | 36 | sum = a + b; 37 | 38 | if (sum < 0) { 39 | flag = 1; 40 | } 41 | sprintf(s, "%d", sum); 42 | 43 | str_len = strlen(s); 44 | 45 | for (i = str_len - 1; i >= 0; i--) { 46 | c[cnt++] = s[i]; 47 | cc++; 48 | if (cc % 3 == 0) { 49 | if (i != 0) { 50 | if (!flag || i != 1) { 51 | c[cnt++] = ','; 52 | cc = 0; 53 | } 54 | } 55 | } 56 | } 57 | 58 | for (i = cnt - 1; i >= 0; i--) { 59 | printf("%c", c[i]); 60 | } 61 | return 0; 62 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1001.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1001 害死人不偿命的(3n+1)猜想 (15)(15 分) 3 | 4 | 卡拉兹(Callatz)猜想: 5 | 6 | 对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。这样一直反复砍下去,最后一定在某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想,传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展…… 7 | 8 | 我们今天的题目不是证明卡拉兹猜想,而是对给定的任一不超过1000的正整数n,简单地数一下,需要多少步(砍几下)才能得到n=1? 9 | 10 | 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。 11 | 12 | 输出格式:输出从n计算到1需要的步数。 13 | 14 | 输入样例: 15 | 16 | 3 17 | 18 | 输出样例: 19 | 20 | 5 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | int main(void) { 27 | int n; 28 | int count = 0; 29 | if (!scanf("%d", &n)) { 30 | return EXIT_FAILURE; 31 | } 32 | 33 | while (n != 1) { 34 | if (n % 2 == 0) { 35 | n = n / 2; 36 | } else { 37 | n = (3 * n + 1) / 2; 38 | } 39 | count++; 40 | } 41 | 42 | printf("%d", count); 43 | return EXIT_SUCCESS; 44 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1002.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1002 写出这个数 (20)(20 分) 3 | 4 | 读入一个自然数n,计算其各位数字之和,用汉语拼音写出和的每一位数字。 5 | 6 | 输入格式:每个测试输入包含1个测试用例,即给出自然数n的值。这里保证n小于10^100^。 7 | 8 | 输出格式:在一行内输出n的各位数字之和的每一位,拼音数字间有1 空格,但一行中最后一个拼音数字后没有空格。 9 | 10 | 输入样例: 11 | 12 | 1234567890987654321123456789 13 | 14 | 输出样例: 15 | 16 | yi san wu 17 | */ 18 | #include 19 | #include 20 | 21 | int main(void) { 22 | int sum = 0; 23 | int i = 0; 24 | char number[11][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"}; 25 | 26 | char c, a[10] = {'\0'}; 27 | 28 | while ((c = getchar()) != EOF) { 29 | if (c == '\n') { 30 | break; 31 | } else { 32 | sum += c - '0'; 33 | } 34 | } 35 | 36 | sprintf(a, "%d", sum); 37 | 38 | for (i = 0; a[i] != '\0'; i++) { 39 | if (i != 0) { 40 | printf(" "); 41 | } 42 | printf("%s", number[a[i] - '0']); 43 | } 44 | return EXIT_SUCCESS; 45 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1003.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1003 我要通过!(20)(20 分) 3 | 4 | “答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”。 5 | 6 | 得到“答案正确”的条件是: 7 | 8 | 1. 字符串中必须仅有P, A, T这三种字符,不可以包含其它字符;\ 9 | 10 | 任意形如 xPATx 的字符串都可以获得“答案正确”,其中 x 或者是空字符串,或者是仅由字母 A 组成的字符串;\ 11 | 如果 aPbTc 是正确的,那么 aPbATca 也是正确的,其中 a, b, c 均或者是空字符串,或者是仅由字母 A 组成的字符串。 12 | 13 | 现在就请你为PAT写一个自动裁判程序,判定哪些字符串是可以获得“答案正确”的。 14 | 15 | 输入格式: 每个测试输入包含1个测试用例。第1行给出一个自然数n (<10),是需要检测的字符串个数。接下来每个字符串占一行,字符串长度不超过100,且不包含空格。 16 | 17 | 输出格式:每个字符串的检测结果占一行,如果该字符串可以获得“答案正确”,则输出YES,否则输出NO。 18 | 19 | 输入样例: 20 | 21 | 8 22 | PAT 23 | PAAT 24 | AAPATAA 25 | AAPAATAAAA 26 | xPATx 27 | PT 28 | Whatever 29 | APAAATAA 30 | 31 | 输出样例: 32 | 33 | YES 34 | YES 35 | YES 36 | YES 37 | NO 38 | NO 39 | NO 40 | NO 41 | */ 42 | #include 43 | #include 44 | 45 | int main(void) { 46 | int number = 0; 47 | int i = 0; 48 | int j = 0; 49 | int flag = 0; 50 | int h_c = 0; 51 | int m_c = 0; 52 | int t_c = 0; 53 | int fflag = 0; 54 | int p_cc = 0; 55 | int t_cc = 0; 56 | 57 | char strlist[10][101]; 58 | 59 | if (!scanf("%d", &number)) { 60 | return EXIT_FAILURE; 61 | } 62 | 63 | if (number > 10 || number < 0) { 64 | return EXIT_FAILURE; 65 | } 66 | 67 | for (i = 0; i < number; i++) { 68 | if (!scanf("%100s", strlist[i])) { 69 | return EXIT_FAILURE; 70 | } 71 | } 72 | 73 | for (i = 0; i < number; i++) { 74 | j = 0; 75 | flag = 0; 76 | h_c = 0; 77 | m_c = 0; 78 | t_c = 0; 79 | fflag = 0; 80 | p_cc = 0; 81 | t_cc = 0; 82 | 83 | while (strlist[i][j] != '\0') { 84 | if (strlist[i][j] == 'P') { 85 | flag = 1; 86 | p_cc++; 87 | } else if (strlist[i][j] == 'T') { 88 | flag = 2; 89 | t_cc++; 90 | } else if (strlist[i][j] == 'A') { 91 | if (flag == 0) { 92 | h_c++; 93 | } else if (flag == 1) { 94 | m_c++; 95 | } else if (flag == 2) { 96 | t_c++; 97 | } 98 | } else { 99 | fflag = 1; 100 | } 101 | j++; 102 | } 103 | 104 | if ((fflag != 1) && (p_cc == 1) && (t_cc == 1) && (m_c != 0) && t_c == (h_c * m_c)) { 105 | printf("YES\n"); 106 | } else { 107 | printf("NO\n"); 108 | } 109 | 110 | } 111 | 112 | return EXIT_SUCCESS; 113 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1004.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1004 成绩排名 (20)(20 分) 3 | 4 | 读入n名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。 5 | 6 | 输入格式:每个测试输入包含1个测试用例,格式为\ 7 | 8 | 第1行:正整数n 9 | 第2行:第1个学生的姓名 学号 成绩 10 | 第3行:第2个学生的姓名 学号 成绩 11 | ... ... ... 12 | 第n+1行:第n个学生的姓名 学号 成绩 13 | 14 | 其中姓名和学号均为不超过10个字符的字符串,成绩为0到100之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。 15 | 16 | 输出格式:对每个测试用例输出2行,第1行是成绩最高学生的姓名和学号,第2行是成绩最低学生的姓名和学号,字符串间有1空格。 17 | 18 | 输入样例: 19 | 20 | 3 21 | Joe Math990112 89 22 | Mike CS991301 100 23 | Mary EE990830 95 24 | 25 | 输出样例: 26 | 27 | Mike CS991301 28 | Joe Math990112 29 | */ 30 | 31 | #include 32 | #include 33 | 34 | struct student { 35 | char name[11]; 36 | char number[11]; 37 | int score; 38 | } s[101]; 39 | 40 | int main(void) { 41 | int n; 42 | int i; 43 | int r[2][2] = {{0, 0}, {0, 0}}; 44 | 45 | if (!scanf("%d", &n)) { 46 | return EXIT_FAILURE; 47 | } 48 | 49 | for (i = 0; i < n; i++) { 50 | if (!scanf("%s %s %d", s[i].name, s[i].number, &(s[i].score))) { 51 | return EXIT_FAILURE; 52 | } 53 | if (i != 0) { 54 | if (s[i].score > r[1][1]) { 55 | r[1][0] = i; 56 | r[1][1] = s[i].score; 57 | } 58 | if (s[i].score < r[0][1]) { 59 | r[0][0] = i; 60 | r[0][1] = s[i].score; 61 | } 62 | } else { 63 | r[0][1] = s[i].score; 64 | r[1][1] = s[i].score; 65 | } 66 | } 67 | 68 | for (i = 1; i >= 0; i--) { 69 | printf("%s %s\n", s[r[i][0]].name, s[r[i][0]].number); 70 | } 71 | return EXIT_SUCCESS; 72 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1005.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1005 继续(3n+1)猜想 (25)(25 分) 3 | 4 | 卡拉兹(Callatz)猜想已经在1001中给出了描述。在这个题目里,情况稍微有些复杂。 5 | 6 | 当我们验证卡拉兹猜想的时候,为了避免重复计算,可以记录下递推过程中遇到的每一个数。例如对n=3进行验证的时候,我们需要计算3、5、8、4、2、1,则当我们对n=5、8、4、2进行验证的时候,就可以直接判定卡拉兹猜想的真伪,而不需要重复计算,因为这4个数已经在验证3的时候遇到过了,我们称5、8、4、2是被3“覆盖”的数。我们称一个数列中的某个数n为“关键数”,如果n不能被数列中的其他数字所覆盖。 7 | 8 | 现在给定一系列待验证的数字,我们只需要验证其中的几个关键数,就可以不必再重复验证余下的数字。你的任务就是找出这些关键数字,并按从大到小的顺序输出它们。 9 | 10 | 输入格式:每个测试输入包含1个测试用例,第1行给出一个正整数K(<100),第2行给出K个互不相同的待验证的正整数n(1<n<=100)的值,数字间用空格隔开。 11 | 12 | 输出格式:每个测试用例的输出占一行,按从大到小的顺序输出关键数字。数字间用1个空格隔开,但一行中最后一个数字后没有空格。 13 | 14 | 输入样例: 15 | 16 | 6 17 | 3 5 6 7 8 11 18 | 19 | 输出样例: 20 | 21 | 7 6 22 | */ 23 | 24 | #include 25 | #include 26 | 27 | int delete(int *array, int a, int len); 28 | 29 | int main () 30 | { 31 | int quantity; 32 | int originalData[100]; 33 | int restData[100]; 34 | int i, restLen, tmp, r, j; 35 | 36 | if (!scanf("%d", &quantity)) { 37 | return EXIT_FAILURE; 38 | } 39 | 40 | for (i = 0; i < quantity; i++) { 41 | if (!scanf("%d", &originalData[i])) { 42 | return EXIT_FAILURE; 43 | } 44 | restData[i] = originalData[i]; 45 | } 46 | 47 | restLen = quantity; 48 | 49 | for (i = 0; i < quantity; i++) { 50 | tmp = originalData[i]; 51 | while (tmp != 1) { 52 | if (tmp % 2 == 0) { 53 | tmp /= 2; 54 | } else { 55 | tmp = (3 * tmp + 1) / 2; 56 | } 57 | r = delete(restData, tmp, restLen); 58 | restLen -= r; 59 | } 60 | } 61 | 62 | 63 | for (i = 0; i < restLen; i++) { 64 | for (j = 0; j < (restLen - i - 1); j++) { 65 | if(restData[j] < restData[j+1]) { 66 | tmp = restData[j+1]; 67 | restData[j+1] = restData[j]; 68 | restData[j] = tmp; 69 | } 70 | } 71 | } 72 | 73 | for (i = 0; i < restLen; i++) { 74 | printf("%d%c", restData[i], i == restLen - 1 ? '\0' : ' '); 75 | } 76 | return EXIT_SUCCESS; 77 | } 78 | 79 | int delete(int *array, int a, int len) { 80 | int i = 0; 81 | int j = 0; 82 | int r = 0; 83 | 84 | for (i = 0; i < len; i++) { 85 | if (array[i] == a) { 86 | for (j = i; j < len; j++) { 87 | array[j] = array[j+1]; 88 | } 89 | r++; 90 | } 91 | } 92 | return r; 93 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1006.c: -------------------------------------------------------------------------------- 1 | /*1006 换个格式输出整数 (15)(15 分) 2 | 3 | 让我们用字母B来表示“百”、字母S表示“十”,用“12...n”来表示个位数字n(<10),换个格式来输出任一个不超过3位的正整数。例如234应该被输出为BBSSS1234,因为它有2个“百”、3个“十”、以及个位的4。 4 | 5 | 输入格式:每个测试输入包含1个测试用例,给出正整数n(<1000)。 6 | 7 | 输出格式:每个测试用例的输出占一行,用规定的格式输出n。 8 | 9 | 输入样例1: 10 | 11 | 234 12 | 13 | 输出样例1: 14 | 15 | BBSSS1234 16 | 17 | 输入样例2: 18 | 19 | 23 20 | 21 | 输出样例2: 22 | 23 | SS123 24 | */ 25 | 26 | #include 27 | #include 28 | #include 29 | 30 | int main () 31 | { 32 | char number[4]; 33 | int len, n; 34 | int j, i = 0; 35 | char c, cc; 36 | char str[3] = {'S','B'}; 37 | 38 | if (!scanf("%3s", number)) { 39 | return EXIT_FAILURE; 40 | } 41 | len = strlen(number); 42 | int flag = len - 1; 43 | 44 | while ((c = number[i]) != '\0') { 45 | n = c - '0'; 46 | 47 | if (flag > 0) { 48 | for (j = 0; j < n; j++) { 49 | cc = str[flag - 1]; 50 | printf("%c", cc); 51 | } 52 | flag--; 53 | } else { 54 | for (j = 0; j < n; j++) { 55 | cc = j + 1 + '0'; 56 | printf("%c", cc); 57 | } 58 | } 59 | 60 | i++; 61 | } 62 | return EXIT_SUCCESS; 63 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1007.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1007 素数对猜想 (20)(20 分) 3 | 4 | 让我们定义 d~n~ 为:d~n~ = p~n+1~ - p~n~,其中 p~i~ 是第i个素数。显然有 d~1~=1 且对于n>1有 d~n~ 是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。 5 | 6 | 现给定任意正整数N (< 10^5^),请计算不超过N的满足猜想的素数对的个数。 7 | 8 | 输入格式:每个测试输入包含1个测试用例,给出正整数N。 9 | 10 | 输出格式:每个测试用例的输出占一行,不超过N的满足猜想的素数对的个数。 11 | 12 | 输入样例: 13 | 14 | 20 15 | 16 | 输出样例: 17 | 18 | 4 19 | */ 20 | #include 21 | #include 22 | #include 23 | 24 | int isPrime(int number); 25 | 26 | int main () 27 | { 28 | int max, prevPrime; 29 | int i = 0, count = 0; 30 | 31 | if (!scanf("%d", &max)) { 32 | return EXIT_FAILURE; 33 | } 34 | 35 | for (i = 1; i <= max; i++) { 36 | if (isPrime(i)) { 37 | if (i - prevPrime == 2) { 38 | count++; 39 | } 40 | prevPrime = i; 41 | } 42 | } 43 | 44 | printf("%d", count); 45 | 46 | return EXIT_SUCCESS; 47 | } 48 | 49 | int isPrime(int number) 50 | { 51 | int i; 52 | int max; 53 | max = sqrt(number); 54 | for (i = 2; i <= max; i++) { 55 | if (number % i == 0) { 56 | return 0; 57 | } 58 | } 59 | 60 | return 1; 61 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1008.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1008 数组元素循环右移问题 (20)(20 分) 3 | 4 | 一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A中的数据由(A~0~ A~1~……A~N-1~)变换为(A~N-M~ …… A~N-1~ A~0~ A~1~……A~N-M-1~)(最后M个数循环移至最前面的M个位置)。如果需要考虑程序移动数据的次数尽量少,要如何设计移动的方法? 5 | 6 | 输入格式:每个输入包含一个测试用例,第1行输入N ( 1<=N<=100)、M(M>=0);第2行输入N个整数,之间用空格分隔。 7 | 8 | 输出格式:在一行中输出循环右移M位以后的整数序列,之间用空格分隔,序列结尾不能有多余空格。 9 | 10 | 输入样例: 11 | 12 | 6 2 13 | 1 2 3 4 5 6 14 | 15 | 输出样例: 16 | 17 | 5 6 1 2 3 4 18 | */ 19 | #include 20 | #include 21 | 22 | void rightMove(int *array, int len); 23 | 24 | int main () 25 | { 26 | int n, m, i; 27 | int array[100]; 28 | 29 | if (!scanf("%d%d", &n, &m)) { 30 | return EXIT_FAILURE; 31 | } 32 | 33 | for (i = 0; i < n; i++) { 34 | if (!scanf("%d", &array[i])) { 35 | return EXIT_FAILURE; 36 | } 37 | } 38 | 39 | for (i = 0; i < m; i++) { 40 | rightMove(array, n); 41 | } 42 | 43 | for (i = 0; i < n; i++) { 44 | printf("%d%c", array[i], i == n - 1 ? '\0' : ' '); 45 | } 46 | 47 | return EXIT_SUCCESS; 48 | } 49 | 50 | void rightMove(int *array, int len) 51 | { 52 | int i, tmp; 53 | 54 | tmp = array[len - 1]; 55 | for (i = len - 1; i > 0; i--) { 56 | array[i] = array[i-1]; 57 | } 58 | array[0] = tmp; 59 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1009.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1009 说反话 (20)(20 分) 3 | 4 | 给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。 5 | 6 | 输入格式:测试输入包含一个测试用例,在一行内给出总长度不超过80的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用1个空格分开,输入保证句子末尾没有多余的空格。 7 | 8 | 输出格式:每个测试用例的输出占一行,输出倒序后的句子。 9 | 10 | 输入样例: 11 | 12 | Hello World Here I Come 13 | 14 | 输出样例: 15 | 16 | Come I Here World Hello 17 | */ 18 | #include 19 | #include 20 | #include 21 | 22 | 23 | int main () 24 | { 25 | char str[81]; 26 | char tmp[81]; 27 | 28 | int i = 0, j, strLen = 0, count = 0, z = 0; 29 | char c; 30 | 31 | 32 | while ((c = getchar()) != '\n') { 33 | str[strLen++] = c; 34 | } 35 | str[strLen] = '\0'; 36 | 37 | 38 | for (i = strLen - 1; i >= 0; i--) { 39 | if (isspace(str[i]) || i == 0) { 40 | for (j = i; j < i + count + 1; j++) { 41 | if (!isspace(str[j])) { 42 | tmp[z++] = str[j]; 43 | } 44 | } 45 | if (i != 0) { 46 | tmp[z++] = ' '; 47 | } 48 | count = 0; 49 | } else { 50 | count++; 51 | } 52 | } 53 | tmp[z] = '\0'; 54 | 55 | printf("%s", tmp); 56 | 57 | return EXIT_SUCCESS; 58 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1010.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1010 一元多项式求导 (25)(25 分) 3 | 4 | 设计函数求一元多项式的导数。(注:x^n^(n为整数)的一阶导数为n*x^n-1^。) 5 | 6 | 输入格式:以指数递降方式输入多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。 7 | 8 | 输出格式:以与输入相同的格式输出导数多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。注意“零多项式”的指数和系数都是0,但是表示为“0 0”。 9 | 10 | 输入样例: 11 | 12 | 3 4 -5 2 6 1 -2 0 13 | 14 | 输出样例: 15 | 16 | 12 3 -10 1 6 0 17 | 18 | */ 19 | #include 20 | #include 21 | #include 22 | 23 | 24 | int main () 25 | { 26 | int coe[1000]; 27 | int exp[1000]; 28 | int cnt = 0, i, cc = 0; 29 | 30 | while (scanf("%d %d", &coe[cnt], &exp[cnt])) { 31 | if (exp[cnt] == 0) { 32 | break; 33 | } 34 | cnt++; 35 | } 36 | 37 | if (exp[0] == 0) { 38 | printf("0 0"); 39 | } else { 40 | for (i = 0; i < cnt; i++) { 41 | if (exp[i] - 1 >= 0) { 42 | coe[i] = coe[i] * exp[i]; 43 | exp[i] = exp[i] - 1; 44 | cc++; 45 | } 46 | 47 | } 48 | 49 | for (i = 0; i < cc; i++) { 50 | printf("%d ", coe[i]); 51 | printf("%d%c", exp[i], i == cc - 1 ? '\0' : ' '); 52 | } 53 | } 54 | 55 | 56 | return EXIT_SUCCESS; 57 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1011.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1011 A+B和C (15)(15 分) 3 | 4 | 给定区间[-2^31^, 2^31^]内的3个整数A、B和C,请判断A+B是否大于C。 5 | 6 | 输入格式: 7 | 8 | 输入第1行给出正整数T(<=10),是测试用例的个数。随后给出T组测试用例,每组占一行,顺序给出A、B和C。整数间以空格分隔。 9 | 10 | 输出格式: 11 | 12 | 对每组测试用例,在一行中输出“Case #X: true”如果A+B>C,否则输出“Case #X: false”,其中X是测试用例的编号(从1开始)。 13 | 14 | 输入样例: 15 | 16 | 4 17 | 1 2 3 18 | 2 3 4 19 | 2147483647 0 2147483646 20 | 0 -2147483648 -2147483647 21 | 22 | 输出样例: 23 | 24 | Case #1: false 25 | Case #2: true 26 | Case #3: true 27 | Case #4: false 28 | */ 29 | #include 30 | #include 31 | 32 | struct caseA { 33 | long a; 34 | long b; 35 | long c; 36 | }; 37 | 38 | int main () 39 | { 40 | int number = 0; 41 | int i = 0; 42 | struct caseA ca[10]; 43 | char *boolean; 44 | 45 | if (!scanf("%d", &number)) { 46 | return EXIT_FAILURE; 47 | } 48 | 49 | for (i = 0; i < number; i++) { 50 | if (!scanf("%ld%ld%ld", &ca[i].a, &ca[i].b, &ca[i].c)) { 51 | return EXIT_FAILURE; 52 | } 53 | } 54 | for (i = 0; i < number; i++) { 55 | if (ca[i].a + ca[i].b > ca[i].c) { 56 | boolean = "true"; 57 | } else { 58 | boolean = "false"; 59 | } 60 | printf("Case #%d: %s\n", i+1, boolean); 61 | } 62 | return EXIT_SUCCESS; 63 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1012.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1012 数字分类(20 分) 3 | 4 | 给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字: 5 | 6 | A​1​​ = 能被 5 整除的数字中所有偶数的和; 7 | A​2​​ = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n​1​​−n​2​​+n​3​​−n​4​​⋯; 8 | A​3​​ = 被 5 除后余 2 的数字的个数; 9 | A​4​​ = 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位; 10 | A​5​​ = 被 5 除后余 4 的数字中最大数字。 11 | 12 | 输入格式: 13 | 14 | 每个输入包含 1 个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数。数字间以空格分隔。 15 | 输出格式: 16 | 17 | 对给定的 N 个正整数,按题目要求计算 A​1​​~A​5​​ 并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。 18 | 19 | 若其中某一类数字不存在,则在相应位置输出 N。 20 | 输入样例 1: 21 | 22 | 13 1 2 3 4 5 6 7 8 9 10 20 16 18 23 | 24 | 输出样例 1: 25 | 26 | 30 11 2 9.7 9 27 | 28 | 输入样例 2: 29 | 30 | 8 1 2 4 5 6 7 9 16 31 | 32 | 输出样例 2: 33 | 34 | N 11 2 N 9 35 | 36 | */ 37 | 38 | #include 39 | #include 40 | 41 | int isEven(int n); 42 | 43 | int main() 44 | { 45 | int number; 46 | int i, nList[1000]; 47 | 48 | int zeroCnt = 0, oneCnt = 0, twoCnt = 0, threeCnt = 0, fourCnt = 0; 49 | int evenSum = 0, oneSum, threeSum = 0, fourMax = 0; 50 | 51 | if (!scanf("%d", &number)) { 52 | return EXIT_FAILURE; 53 | } 54 | 55 | for (i = 0; i < number; i++) { 56 | if (!scanf("%d", &nList[i])) { 57 | return EXIT_FAILURE; 58 | } 59 | } 60 | 61 | for (i = 0; i < number; i++) { 62 | switch (nList[i] % 5) { 63 | case 0: 64 | if (isEven(nList[i])) { 65 | zeroCnt++; 66 | evenSum += nList[i]; 67 | } 68 | break; 69 | case 1: 70 | oneCnt++; 71 | if (oneCnt % 2 == 1) { 72 | oneSum += nList[i]; 73 | } else { 74 | oneSum -= nList[i]; 75 | } 76 | break; 77 | case 2: 78 | twoCnt++; 79 | break; 80 | case 3: 81 | threeSum += nList[i]; 82 | threeCnt++; 83 | break; 84 | case 4: 85 | fourCnt++; 86 | if (nList[i] > fourMax) { 87 | fourMax = nList[i]; 88 | } 89 | break; 90 | } 91 | } 92 | 93 | if (zeroCnt == 0) { 94 | printf("N "); 95 | } else { 96 | printf("%d ", evenSum); 97 | } 98 | 99 | if (oneCnt == 0) { 100 | printf("N "); 101 | } else { 102 | printf("%d ", oneSum); 103 | } 104 | 105 | if (twoCnt == 0) { 106 | printf("N "); 107 | } else { 108 | printf("%d ", twoCnt); 109 | } 110 | 111 | if (threeCnt == 0) { 112 | printf("N "); 113 | } else { 114 | printf("%.1f ", threeSum / (threeCnt * 1.0)); 115 | } 116 | 117 | if (fourCnt == 0) { 118 | printf("N"); 119 | } else { 120 | printf("%d", fourMax); 121 | } 122 | 123 | return EXIT_SUCCESS; 124 | } 125 | 126 | int isEven(int n) 127 | { 128 | if (n % 2 == 0) { 129 | return 1; 130 | } 131 | return 0; 132 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1013.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1013 数素数 (20)(20 分) 3 | 4 | 令P~i~表示第i个素数。现任给两个正整数M <= N <= 10^4^,请输出P~M~到P~N~的所有素数。 5 | 6 | 输入格式: 7 | 8 | 输入在一行中给出M和N,其间以空格分隔。 9 | 10 | 输出格式: 11 | 12 | 输出从P~M~到P~N~的所有素数,每10个数字占1行,其间以空格分隔,但行末不得有多余空格。 13 | 14 | 输入样例: 15 | 16 | 5 27 17 | 18 | 输出样例: 19 | 20 | 11 13 17 19 23 29 31 37 41 43 21 | 47 53 59 61 67 71 73 79 83 89 22 | 97 101 103 23 | 24 | 注意审题:是第5到第27个素数 25 | */ 26 | #include 27 | #include 28 | #include 29 | 30 | 31 | int isPrime(int n); 32 | 33 | int main () 34 | { 35 | int start, end; 36 | int i, cnt = 0, ccnt = 0; 37 | 38 | if (!scanf("%d%d", &start, &end)) { 39 | return EXIT_FAILURE; 40 | } 41 | 42 | i = 2; 43 | 44 | while (cnt < end) { 45 | if (isPrime(i)) { 46 | cnt++; 47 | if (cnt >= start) { 48 | if (ccnt % 10 == 0) { 49 | if (ccnt != 0) { 50 | printf("\n%d", i); 51 | } else { 52 | printf("%d", i); 53 | } 54 | } else { 55 | printf(" %d", i); 56 | } 57 | ccnt++; 58 | } 59 | } 60 | i++; 61 | } 62 | 63 | return EXIT_SUCCESS; 64 | } 65 | 66 | int isPrime(int n) 67 | { 68 | int i; 69 | for (i = 2; i <= sqrt(n); i++) { 70 | if (n % i == 0) { 71 | return 0; 72 | } 73 | } 74 | return 1; 75 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1014.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1014 福尔摩斯的约会 (20)(20 分) 3 | 4 | 大侦探福尔摩斯接到一张奇怪的字条:“我们约会吧! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm”。大侦探很快就明白了,字条上奇怪的乱码实际上就是约会的时间“星期四 14:04”,因为前面两字符串中第1对相同的大写英文字母(大小写有区分)是第4个字母'D',代表星期四;第2对相同的字符是'E',那是第5个英文字母,代表一天里的第14个钟头(于是一天的0点到23点由数字0到9、以及大写字母A到N表示);后面两字符串第1对相同的英文字母's'出现在第4个位置(从0开始计数)上,代表第4分钟。现给定两对字符串,请帮助福尔摩斯解码得到约会的时间。 5 | 6 | 输入格式: 7 | 8 | 输入在4行中分别给出4个非空、不包含空格、且长度不超过60的字符串。 9 | 10 | 输出格式: 11 | 12 | 在一行中输出约会的时间,格式为“DAY HH:MM”,其中“DAY”是某星期的3字符缩写,即MON表示星期一,TUE表示星期二,WED表示星期三,THU表示星期四,FRI表示星期五,SAT表示星期六,SUN表示星期日。题目输入保证每个测试存在唯一解。 13 | 14 | 输入样例: 15 | 16 | 3485djDkxh4hhGE 17 | 2984akDfkkkkggEdsb 18 | s&hgsfdk 19 | d&Hyscvnm 20 | 21 | 输出样例: 22 | 23 | THU 14:04 24 | 25 | 注意:注意下相同的字符的范围 26 | 1.A-G 27 | 2.0-9或A-N 28 | 3.A-Z或a-z 29 | */ 30 | #include 31 | #include 32 | #include 33 | 34 | 35 | struct vp{ 36 | char value; 37 | int pos; 38 | }; 39 | 40 | int main () 41 | { 42 | struct vp vv[4]; 43 | 44 | char ss[4][61]; 45 | int i, vcnt = 0; 46 | char weeks[7][4] = {"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"}; 47 | 48 | int week, hour, minutes; 49 | 50 | for (i = 0; i < 4; i++) { 51 | if (!scanf("%s", ss[i])) { 52 | return EXIT_FAILURE; 53 | } 54 | } 55 | 56 | i = 0; 57 | while (ss[0][i] != '\0' && ss[1][i] != '\0') { 58 | if ((ss[0][i] == ss[1][i])) { 59 | if (vcnt < 2) { 60 | if ((vcnt == 0) && (ss[0][i] >= 'A' && ss[0][i] <= 'G')) { 61 | vv[vcnt].value = ss[0][i]; 62 | vv[vcnt].pos = i; 63 | vcnt++; 64 | } else if ((vcnt == 1) && ((ss[0][i] >= '0' && ss[0][i] <= '9') || (ss[0][i] >= 'A' && ss[0][i] <= 'N'))) { 65 | vv[vcnt].value = ss[0][i]; 66 | vv[vcnt].pos = i; 67 | vcnt++; 68 | } 69 | 70 | } else { 71 | break; 72 | } 73 | } 74 | i++; 75 | } 76 | 77 | i = 0; 78 | while (ss[2][i] != '\0' && ss[3][i] != '\0') { 79 | if (ss[2][i] == ss[3][i] && ss[2][i] >= 'A' && ss[3][i] <= 'z') { 80 | if (vcnt < 3) { 81 | vv[vcnt].value = ss[2][i]; 82 | vv[vcnt].pos = i; 83 | } else { 84 | break; 85 | } 86 | vcnt++; 87 | } 88 | i++; 89 | } 90 | 91 | 92 | if (vv[0].value <= 'Z' && vv[0].value >= 'A') { 93 | week = vv[0].value - 'A'; 94 | } else { 95 | week = vv[0].value - 'a'; 96 | } 97 | 98 | if (vv[1].value >= 'A' && vv[1].value <= 'N') { 99 | hour = vv[1].value - 'A' + 10; 100 | } else if (vv[1].value >= 'a' && vv[1].value <= 'z') { 101 | hour = vv[1].value - 'a' + 10; 102 | } else { 103 | hour = vv[1].value - '0'; 104 | } 105 | 106 | minutes = vv[2].pos; 107 | 108 | printf("%s%s%d%s%d", weeks[week], hour < 10 ? " 0" : " ", hour, minutes < 10 ? ":0" : ":", minutes); 109 | return EXIT_SUCCESS; 110 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1015.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1015 德才论(25 分) 3 | 4 | 宋代史学家司马光在《资治通鉴》中有一段著名的“德才论”:“是故才德全尽谓之圣人,才德兼亡谓之愚人,德胜才谓之君子,才胜德谓之小人。凡取人之术,苟不得圣人,君子而与之,与其得小人,不若得愚人。” 5 | 6 | 现给出一批考生的德才分数,请根据司马光的理论给出录取排名。 7 | 输入格式: 8 | 9 | 输入第一行给出 3 个正整数,分别为:N(≤10​5​​),即考生总数;L(≥60),为录取最低分数线,即德分和才分均不低于 L 的考生才有资格被考虑录取;H(<100),为优先录取线——德分和才分均不低于此线的被定义为“才德全尽”,此类考生按德才总分从高到低排序;才分不到但德分到线的一类考生属于“德胜才”,也按总分排序,但排在第一类考生之后;德才分均低于 H,但是德分不低于才分的考生属于“才德兼亡”但尚有“德胜才”者,按总分排序,但排在第二类考生之后;其他达到最低线 L 的考生也按总分排序,但排在第三类考生之后。 10 | 11 | 随后 N 行,每行给出一位考生的信息,包括:准考证号 德分 才分,其中准考证号为 8 位整数,德才分为区间 [0, 100] 内的整数。数字间以空格分隔。 12 | 输出格式: 13 | 14 | 输出第一行首先给出达到最低分数线的考生人数 M,随后 M 行,每行按照输入格式输出一位考生的信息,考生按输入中说明的规则从高到低排序。当某类考生中有多人总分相同时,按其德分降序排列;若德分也并列,则按准考证号的升序输出。 15 | 输入样例: 16 | 17 | 14 60 80 18 | 10000001 64 90 19 | 10000002 90 60 20 | 10000011 85 80 21 | 10000003 85 80 22 | 10000004 80 85 23 | 10000005 82 77 24 | 10000006 83 76 25 | 10000007 90 78 26 | 10000008 75 79 27 | 10000009 59 90 28 | 10000010 88 45 29 | 10000012 80 100 30 | 10000013 90 99 31 | 10000014 66 60 32 | 33 | 输出样例: 34 | 35 | 12 36 | 10000013 90 99 37 | 10000012 80 100 38 | 10000003 85 80 39 | 10000011 85 80 40 | 10000004 80 85 41 | 10000007 90 78 42 | 10000006 83 76 43 | 10000005 82 77 44 | 10000002 90 60 45 | 10000014 66 60 46 | 10000008 75 79 47 | 10000001 64 90 48 | 49 | */ 50 | 51 | #include 52 | #include 53 | 54 | typedef struct { 55 | int number; 56 | int de; 57 | int cai; 58 | int total; 59 | } ss; 60 | 61 | int m_cmp(const void *a, const void *b); 62 | 63 | int main() 64 | { 65 | ss t[4][100000]; 66 | 67 | int total, low, high, i, j; 68 | int number, de, cai, total_n; 69 | int hg[4], index; 70 | int hege = 0; 71 | 72 | if (!scanf("%d %d %d", &total, &low, &high)) { 73 | return 1; 74 | } 75 | 76 | for (i = 0; i < total; i++) { 77 | if (!scanf("%d %d %d", &number, &de, &cai)) { 78 | return 1; 79 | } 80 | if (de >= low && cai >= low) { 81 | total_n = de + cai; 82 | 83 | if (de >= high && cai >= high) { 84 | index = 0; 85 | } else if (de >= high && cai < high) { 86 | index = 1; 87 | } else if (de >= cai) { 88 | index = 2; 89 | } else { 90 | index = 3; 91 | } 92 | t[index][hg[index]].number = number; 93 | t[index][hg[index]].de = de; 94 | t[index][hg[index]].cai = cai; 95 | t[index][hg[index]].total = total_n; 96 | hg[index]++; 97 | hege++; 98 | } 99 | } 100 | 101 | for (i = 0; i < 4; i++) { 102 | qsort(&t[i], hg[i], sizeof(ss), m_cmp); 103 | } 104 | printf("%d\n", hege); 105 | for (i = 0; i < 4; i++) { 106 | for (j = 0; j < hg[i]; j++) { 107 | printf("%d %d %d\n", t[i][j].number, t[i][j].de, t[i][j].cai); 108 | } 109 | } 110 | return 0; 111 | } 112 | 113 | int m_cmp(const void *a, const void *b) 114 | { 115 | ss *c = (ss *)a; 116 | ss *d = (ss *)b; 117 | if (c->total != d->total) { 118 | return c->total < d->total; 119 | } else if (c->de != d->de) { 120 | return c->de < d->de; 121 | } else { 122 | return c->number > d->number; 123 | } 124 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1016.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1016 部分A+B(15 分)提问 3 | 4 | 正整数 A 的“D​A​​(为 1 位整数)部分”定义为由 A 中所有 D​A​​ 组成的新整数 P​A​​。例如:给定 A=3862767,D​A​​=6,则 A 的“6 部分”P​A​​ 是 66,因为 A 中有 2 个 6。 5 | 6 | 现给定 A、D​A​​、B、D​B​​,请编写程序计算 P​A​​+P​B​​。 7 | 输入格式: 8 | 9 | 输入在一行中依次给出 A、D​A​​、B、D​B​​,中间以空格分隔,其中 0 30 | #include 31 | 32 | int main () 33 | { 34 | char a[10]; 35 | char da; 36 | char b[10]; 37 | char db; 38 | 39 | char c; 40 | int i = 0; 41 | 42 | int a_sum = 0; 43 | int b_sum = 0; 44 | 45 | if (!scanf("%s %c %s %c", a, &da, b, &db)) { 46 | return EXIT_FAILURE; 47 | } 48 | 49 | i = 0; 50 | while ((c = a[i]) != '\0') { 51 | if (a[i] == da) { 52 | a_sum = a_sum * 10 + (da - '0'); 53 | } 54 | i++; 55 | } 56 | 57 | i = 0; 58 | while ((c = b[i]) != '\0') { 59 | if (b[i] == db) { 60 | b_sum = b_sum * 10 + (db - '0'); 61 | } 62 | i++; 63 | } 64 | 65 | printf("%d", a_sum + b_sum); 66 | 67 | return EXIT_SUCCESS; 68 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1017.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1017 A除以B(20 分) 3 | 4 | 本题要求计算 A/B,其中 A 是不超过 1000 位的正整数,B 是 1 位正整数。你需要输出商数 Q 和余数 R,使得 A=B×Q+R 成立。 5 | 输入格式: 6 | 7 | 输入在一行中依次给出 A 和 B,中间以 1 空格分隔。 8 | 输出格式: 9 | 10 | 在一行中依次输出 Q 和 R,中间以 1 空格分隔。 11 | 输入样例: 12 | 13 | 123456789050987654321 7 14 | 15 | 输出样例: 16 | 17 | 17636684150141093474 3 18 | 19 | */ 20 | #include 21 | #include 22 | #include 23 | 24 | int main () 25 | { 26 | char number[1001]; 27 | char quotient[1001]; 28 | int remainder = 0; 29 | int divisor, i = 0, j = 0, current, currentQuotient, stringlen; 30 | 31 | if (!scanf("%s %d", number, &divisor)) { 32 | return EXIT_FAILURE; 33 | } 34 | 35 | stringlen = strlen(number); 36 | 37 | while (number[i] != '\0') { 38 | current = number[i] - '0' + remainder * 10; 39 | currentQuotient = current / divisor; 40 | remainder = current % divisor; 41 | 42 | if (stringlen == 1 || i != 0 || currentQuotient > 0) { 43 | quotient[j++] = currentQuotient + '0'; 44 | } 45 | i++; 46 | } 47 | quotient[j] = '\0'; 48 | 49 | printf("%s %d", quotient, remainder); 50 | 51 | return EXIT_SUCCESS; 52 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1019.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1019 数字黑洞(20 分) 3 | 4 | 给定任一个各位数字不完全相同的 4 位正整数,如果我们先把 4 个数字按非递增排序,再按非递减排序,然后用第 1 个数字减第 2 个数字,将得到一个新的数字。一直重复这样做,我们很快会停在有“数字黑洞”之称的 6174,这个神奇的数字也叫 Kaprekar 常数。 5 | 6 | 例如,我们从6767开始,将得到 7 | 8 | 7766 - 6677 = 1089 9 | 9810 - 0189 = 9621 10 | 9621 - 1269 = 8352 11 | 8532 - 2358 = 6174 12 | 7641 - 1467 = 6174 13 | ... ... 14 | 15 | 现给定任意 4 位正整数,请编写程序演示到达黑洞的过程。 16 | 输入格式: 17 | 18 | 输入给出一个 (0,10​4​​) 区间内的正整数 N。 19 | 输出格式: 20 | 21 | 如果 N 的 4 位数字全相等,则在一行内输出 N - N = 0000;否则将计算的每一步在一行内输出,直到 6174 作为差出现,输出格式见样例。注意每个数字按 4 位数格式输出。 22 | 输入样例 1: 23 | 24 | 6767 25 | 26 | 输出样例 1: 27 | 28 | 7766 - 6677 = 1089 29 | 9810 - 0189 = 9621 30 | 9621 - 1269 = 8352 31 | 8532 - 2358 = 6174 32 | 33 | 输入样例 2: 34 | 35 | 2222 36 | 37 | 输出样例 2: 38 | 39 | 2222 - 2222 = 0000 40 | 41 | */ 42 | 43 | #include 44 | #include 45 | #include 46 | 47 | void m_sort(char *ori, int up); 48 | 49 | int main () 50 | { 51 | char big[5], small[5], r[5]; 52 | int big_i, small_i, r_i = 0; 53 | 54 | if (!scanf("%d", &r_i)) { 55 | return 1; 56 | } 57 | 58 | do { 59 | sprintf(r, "%04d", r_i); 60 | strcpy(big, r); 61 | strcpy(small, big); 62 | m_sort(big, 0); 63 | m_sort(small, 1); 64 | big_i = atoi(big); 65 | small_i = atoi(small); 66 | r_i = big_i - small_i; 67 | printf("%04d - %04d = %04d\n", big_i, small_i, r_i); 68 | 69 | } while ((r_i != 6174) && (big_i != small_i)); 70 | 71 | return 0; 72 | } 73 | 74 | void m_sort(char *ori, int up) 75 | { 76 | int i, j, str_len, t; 77 | 78 | str_len = strlen(ori); 79 | 80 | for (i = 0; i < str_len; i++) { 81 | for (j = 0; j < str_len - i - 1; j++) { 82 | if (up) { 83 | if (ori[j] > ori[j+1]) { 84 | t = ori[j]; 85 | ori[j] = ori[j+1]; 86 | ori[j+1] = t; 87 | } 88 | } else { 89 | if (ori[j] < ori[j+1]) { 90 | t = ori[j]; 91 | ori[j] = ori[j+1]; 92 | ori[j+1] = t; 93 | } 94 | } 95 | 96 | } 97 | } 98 | } 99 | 100 | -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1020.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1020 月饼(25 分) 3 | 4 | 月饼是中国人在中秋佳节时吃的一种传统食品,不同地区有许多不同风味的月饼。现给定所有种类月饼的库存量、总售价、以及市场的最大需求量,请你计算可以获得的最大收益是多少。 5 | 6 | 注意:销售时允许取出一部分库存。样例给出的情形是这样的:假如我们有 3 种月饼,其库存量分别为 18、15、10 万吨,总售价分别为 75、72、45 亿元。如果市场的最大需求量只有 20 万吨,那么我们最大收益策略应该是卖出全部 15 万吨第 2 种月饼、以及 5 万吨第 3 种月饼,获得 72 + 45/2 = 94.5(亿元)。 7 | 输入格式: 8 | 9 | 每个输入包含一个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N 表示月饼的种类数、以及不超过 500(以万吨为单位)的正整数 D 表示市场最大需求量。随后一行给出 N 个正数表示每种月饼的库存量(以万吨为单位);最后一行给出 N 个正数表示每种月饼的总售价(以亿元为单位)。数字间以空格分隔。 10 | 输出格式: 11 | 12 | 对每组测试用例,在一行中输出最大收益,以亿元为单位并精确到小数点后 2 位。 13 | 输入样例: 14 | 15 | 3 20 16 | 18 15 10 17 | 75 72 45 18 | 19 | 输出样例: 20 | 21 | 94.50 22 | 23 | 需要注意的是,moon[i].total_sale * max_need / moon[i].inventory这段代码,因为涉及到浮点数运算,先计算谁对结果的正确性有影响(按说不应该这样,可能pat平台的测试用例的断言只针对一种顺序的计算). 24 | */ 25 | 26 | #include 27 | #include 28 | 29 | typedef struct { 30 | float inventory; 31 | float total_sale; 32 | float price; 33 | } mcake; 34 | 35 | int my_cmp(const void *a, const void *b); 36 | 37 | int main () 38 | { 39 | int category; 40 | int i = 0; 41 | float max = 0, max_need; 42 | mcake moon[1001]; 43 | 44 | 45 | if (!scanf("%d %f", &category, &max_need)) { 46 | return 1; 47 | } 48 | 49 | for (i = 0; i < category; i++) { 50 | if (!scanf("%f", &moon[i].inventory)) { 51 | return 1; 52 | } 53 | } 54 | for (i = 0; i < category; i++) { 55 | if (!scanf("%f", &moon[i].total_sale)) { 56 | return 1; 57 | } 58 | } 59 | 60 | for (i = 0; i < category; i++) { 61 | moon[i].price = moon[i].total_sale / moon[i].inventory; 62 | } 63 | 64 | qsort(&moon, category, sizeof(mcake), my_cmp); 65 | 66 | for (i = 0; i < category; i++) { 67 | if (max_need <= 0) { 68 | break; 69 | } 70 | if (moon[i].inventory <= max_need) { 71 | max += moon[i].total_sale; 72 | max_need -= moon[i].inventory; 73 | } else { 74 | max += (moon[i].total_sale * max_need / moon[i].inventory); 75 | max_need = 0; 76 | } 77 | } 78 | 79 | printf("%.2f", max); 80 | 81 | return 0; 82 | } 83 | 84 | int my_cmp(const void *a, const void *b) { 85 | mcake *c = (mcake *)a; 86 | mcake *d = (mcake *)b; 87 | 88 | return c->price < d->price; 89 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1021.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1021 个位数统计(15 分) 3 | 4 | 给定一个 k 位整数 N=d​k−1​​10​k−1​​+⋯+d​1​​10​1​​+d​0​​ (0≤d​i​​≤9, i=0,⋯,k−1, d​k−1​​>0),请编写程序统计每种不同的个位数字出现的次数。例如:给定 N=100311,则有 2 个 0,3 个 1,和 1 个 3。 5 | 输入格式: 6 | 7 | 每个输入包含 1 个测试用例,即一个不超过 1000 位的正整数 N。 8 | 输出格式: 9 | 10 | 对 N 中每一种不同的个位数字,以 D:M 的格式在一行中输出该位数字 D 及其在 N 中出现的次数 M。要求按 D 的升序输出。 11 | 输入样例: 12 | 13 | 100311 14 | 15 | 输出样例: 16 | 17 | 0:2 18 | 1:3 19 | 3:1 20 | 21 | 22 | */ 23 | #include 24 | #include 25 | 26 | int main () 27 | { 28 | char c; 29 | int count[10], index = 0, i = 0; 30 | for (i = 0; i < 10; i++) { 31 | count[i] = 0; 32 | } 33 | 34 | while ((c = getchar()) != EOF) { 35 | if (c == '\n') { 36 | break; 37 | } 38 | index = c - '0'; 39 | count[index]++; 40 | } 41 | 42 | for (i = 0; i < 10; i++) { 43 | if (count[i] != 0) { 44 | printf("%d:%d\n", i, count[i]); 45 | } 46 | } 47 | return 0; 48 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1022.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1022 D进制的A+B(20 分) 3 | 4 | 输入两个非负 10 进制整数 A 和 B (≤2​30​​−1),输出 A+B 的 D (1 22 | #include 23 | 24 | int main () 25 | { 26 | int a, b, c, d; 27 | int number[32], count = 0, i; 28 | 29 | if (!scanf("%d %d %d", &a, &b, &d)) { 30 | return 1; 31 | } 32 | 33 | c = a + b; 34 | 35 | if (c == 0) { 36 | number[count++] = 0; 37 | } 38 | while (c != 0) { 39 | number[count++] = c % d; 40 | c = c / d; 41 | } 42 | 43 | for (i = count - 1; i >= 0; i--) { 44 | printf("%d", number[i]); 45 | } 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1023.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1023 组个最小数(20 分) 3 | 4 | 给定数字 0-9 各若干个。你可以以任意顺序排列这些数字,但必须全部使用。目标是使得最后得到的数尽可能小(注意 0 不能做首位)。例如:给定两个 0,两个 1,三个 5,一个 8,我们得到的最小的数就是 10015558。 5 | 6 | 现给定数字,请编写程序输出能够组成的最小的数。 7 | 输入格式: 8 | 9 | 输入在一行中给出 10 个非负整数,顺序表示我们拥有数字 0、数字 1、……数字 9 的个数。整数间用一个空格分隔。10 个数字的总个数不超过 50,且至少拥有 1 个非 0 的数字。 10 | 输出格式: 11 | 12 | 在一行中输出能够组成的最小的数。 13 | 输入样例: 14 | 15 | 2 2 0 0 0 3 0 0 1 0 16 | 17 | 输出样例: 18 | 19 | 10015558 20 | 21 | */ 22 | #include 23 | #include 24 | 25 | int main () 26 | { 27 | int number[50]; 28 | int count[10]; 29 | int i, j, sum = 0; 30 | 31 | for (i = 0; i < 10; i++) { 32 | if (!scanf("%d", &count[i])) { 33 | return 1; 34 | } 35 | } 36 | 37 | for (i = 1; i < 10; i++) { 38 | for (j = 0; j < count[i]; j++) { 39 | number[sum++] = i; 40 | } 41 | } 42 | 43 | for (i = 0; i < sum; i++) { 44 | printf("%d", number[i]); 45 | if (i == 0) { 46 | for (j = 0; j < count[0]; j++) { 47 | printf("%d", 0); 48 | } 49 | } 50 | } 51 | return 0; 52 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1024.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1024 科学计数法(20 分) 3 | 4 | 科学计数法是科学家用来表示很大或很小的数字的一种方便的方法,其满足正则表达式 [+-][1-9].[0-9]+E[+-][0-9]+,即数字的整数部分只有 1 位,小数部分至少有 1 位,该数字及其指数部分的正负号即使对正数也必定明确给出。 5 | 6 | 现以科学计数法的格式给出实数 A,请编写程序按普通数字表示法输出 A,并保证所有有效位都被保留。 7 | 输入格式: 8 | 9 | 每个输入包含 1 个测试用例,即一个以科学计数法表示的实数 A。该数字的存储长度不超过 9999 字节,且其指数的绝对值不超过 9999。 10 | 输出格式: 11 | 12 | 对每个测试用例,在一行中按普通数字表示法输出 A,并保证所有有效位都被保留,包括末尾的 0。 13 | 输入样例 1: 14 | 15 | +1.23400E-03 16 | 17 | 输出样例 1: 18 | 19 | 0.00123400 20 | 21 | 输入样例 2: 22 | 23 | -1.2E+10 24 | 25 | 输出样例 2: 26 | 27 | -12000000000 28 | 29 | */ 30 | #include 31 | #include 32 | 33 | int main () 34 | { 35 | char symbol = '+'; 36 | char zheng = '0'; 37 | char xiaoshu[10000]; 38 | int xiao = 0; 39 | 40 | char z_symbol = '+'; 41 | char zhishu[10000]; 42 | int zhi_shu_i; 43 | int zhi = 0; 44 | 45 | char c; 46 | int cnt = 0; 47 | int xiao_flag = 0; 48 | int zhi_flag = 0; 49 | 50 | int i; 51 | 52 | while ((c = getchar()) != EOF) { 53 | if (c == '\n') { 54 | break; 55 | } 56 | if (cnt == 0) { 57 | symbol = c; 58 | } else if (cnt == 1) { 59 | zheng = c; 60 | } 61 | 62 | if (zhi_flag) { 63 | if (c != '-' && c != '+') { 64 | zhishu[zhi++] = c; 65 | } else { 66 | z_symbol = c; 67 | } 68 | } 69 | 70 | if (c == 'E') { 71 | xiao_flag = 0; 72 | zhi_flag = 1; 73 | } 74 | if (xiao_flag) { 75 | xiaoshu[xiao++] = c; 76 | } 77 | if (c == '.') { 78 | xiao_flag = 1; 79 | } 80 | cnt++; 81 | } 82 | 83 | zhi_shu_i = atoi(zhishu); 84 | if (symbol == '-') { 85 | printf("%c", symbol); 86 | } 87 | 88 | if (z_symbol == '-') { 89 | printf("0."); 90 | for (i = 0; i < zhi_shu_i - 1; i++) { 91 | printf("0"); 92 | } 93 | printf("%c", zheng); 94 | printf("%s", xiaoshu); 95 | } else { 96 | if (zhi_shu_i >= xiao) { 97 | printf("%c", zheng); 98 | printf("%s", xiaoshu); 99 | for (i = 0; i < (zhi_shu_i - xiao); i++) { 100 | printf("0"); 101 | } 102 | } else { 103 | printf("%c", zheng); 104 | for (i = 0; i < xiao; i++) { 105 | printf("%c", xiaoshu[i]); 106 | if (i == zhi_shu_i - 1) { 107 | printf("."); 108 | } 109 | } 110 | } 111 | } 112 | 113 | return 0; 114 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1025.c: -------------------------------------------------------------------------------- 1 | /** 2 | 1025 反转链表 (25 分) 3 | 4 | 给定一个常数 K 以及一个单链表 L,请编写程序将 L 中每 K 个结点反转。例如:给定 L 为 1→2→3→4→5→6,K 为 3,则输出应该为 3→2→1→6→5→4;如果 K 为 4,则输出应该为 4→3→2→1→5→6,即最后不到 K 个元素不反转。 5 | 输入格式: 6 | 7 | 每个输入包含 1 个测试用例。每个测试用例第 1 行给出第 1 个结点的地址、结点总个数正整数 N (≤10​5​​)、以及正整数 K (≤N),即要求反转的子链结点的个数。结点的地址是 5 位非负整数,NULL 地址用 −1 表示。 8 | 9 | 接下来有 N 行,每行格式为: 10 | 11 | Address Data Next 12 | 13 | 其中 Address 是结点地址,Data 是该结点保存的整数数据,Next 是下一结点的地址。 14 | 输出格式: 15 | 16 | 对每个测试用例,顺序输出反转后的链表,其上每个结点占一行,格式与输入相同。 17 | 输入样例: 18 | 19 | 00100 6 4 20 | 00000 4 99999 21 | 00100 1 12309 22 | 68237 6 -1 23 | 33218 3 00000 24 | 99999 5 68237 25 | 12309 2 33218 26 | 27 | 输出样例: 28 | 29 | 00000 4 33218 30 | 33218 3 12309 31 | 12309 2 00100 32 | 00100 1 99999 33 | 99999 5 68237 34 | 68237 6 -1 35 | 36 | */ 37 | 38 | 39 | /* 40 | 审题需要注意的地方: 41 | 1.输入的N个节点中有无效的节点,即从起始位置开始,通过next遍历,有些节点不在链表上,无效节点需要舍去. 42 | 2.[每 K 个结点反转]:把链表分成组,每组中有K个节点,反转发生在每一个组内. 43 | 3.[最后不到 K 个元素不反转]:有两种情况,一种是链表总长度不足K,不反转;另一种是按每组K个节点分组,链表最后一组节点数不足K,这一组不反转. 44 | */ 45 | 46 | #include 47 | #include 48 | 49 | typedef struct { 50 | int addr; 51 | int data; 52 | int next; 53 | } node; 54 | 55 | int main () 56 | { 57 | node map[100000]; 58 | node rightMap[100000]; 59 | node rMap[100000]; 60 | 61 | int root, num, k, num_right = 0, tn, nn = 0; 62 | int addr, data, next; 63 | int i, tt; 64 | int cur; 65 | 66 | if (!scanf("%d %d %d", &root, &num, &k)) { 67 | return 1; 68 | } 69 | 70 | for (i = 0; i < num; i++) { 71 | if (!scanf("%d %d %d", &addr, &data, &next)) { 72 | return 1; 73 | } 74 | map[addr].addr = addr; 75 | map[addr].data = data; 76 | map[addr].next = next; 77 | } 78 | 79 | cur = root; 80 | while (cur != -1) { 81 | rightMap[num_right++] = map[cur]; 82 | cur = map[cur].next; 83 | } 84 | 85 | tt = 0; 86 | tn = num_right; 87 | 88 | while (tn >= k) { 89 | tt++; 90 | if (tt % k == 0) { 91 | for (i = tt - 1; i >= tt - k; i--) { 92 | rMap[nn++] = rightMap[i]; 93 | } 94 | tn -= k; 95 | } 96 | } 97 | 98 | for (i = tt; i < num_right; i++) { 99 | rMap[nn++] = rightMap[i]; 100 | } 101 | 102 | for (i = 0; i < num_right - 1; i++) { 103 | printf("%05d %d %05d\n", rMap[i].addr, rMap[i].data, rMap[i+1].addr); 104 | } 105 | printf("%05d %d -1\n", rMap[i].addr, rMap[i].data); 106 | return 0; 107 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1026.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1026 程序运行时间 (15 分) 3 | 4 | 要获得一个 C 语言程序的运行时间,常用的方法是调用头文件 time.h,其中提供了 clock() 函数,可以捕捉从程序开始运行到 clock() 被调用时所耗费的时间。这个时间单位是 clock tick,即“时钟打点”。同时还有一个常数 CLK_TCK,给出了机器时钟每秒所走的时钟打点数。于是为了获得一个函数 f 的运行时间,我们只要在调用 f 之前先调用 clock(),获得一个时钟打点数 C1;在 f 执行完成后再调用 clock(),获得另一个时钟打点数 C2;两次获得的时钟打点数之差 (C2-C1) 就是 f 运行所消耗的时钟打点数,再除以常数 CLK_TCK,就得到了以秒为单位的运行时间。 5 | 6 | 这里不妨简单假设常数 CLK_TCK 为 100。现给定被测函数前后两次获得的时钟打点数,请你给出被测函数运行的时间。 7 | 输入格式: 8 | 9 | 输入在一行中顺序给出 2 个整数 C1 和 C2。注意两次获得的时钟打点数肯定不相同,即 C1 < C2,并且取值在 [0,10​7​​]。 10 | 输出格式: 11 | 12 | 在一行中输出被测函数运行的时间。运行时间必须按照 hh:mm:ss(即2位的 时:分:秒)格式输出;不足 1 秒的时间四舍五入到秒。 13 | 输入样例: 14 | 15 | 123 4577973 16 | 17 | 输出样例: 18 | 19 | 12:42:59 20 | 21 | */ 22 | 23 | #include 24 | #include 25 | 26 | int main () 27 | { 28 | int start, end; 29 | int cha; 30 | int hour, minutes; 31 | 32 | if (!scanf("%d %d", &start, &end)) { 33 | return 1; 34 | } 35 | 36 | cha = end - start; 37 | 38 | if (cha % 100 >= 50) { 39 | cha = cha / 100 + 1; 40 | } else { 41 | cha = cha / 100; 42 | } 43 | 44 | hour = cha / 3600; 45 | cha = cha % 3600; 46 | 47 | minutes = cha / 60; 48 | cha = cha % 60; 49 | 50 | printf("%02d:%02d:%02d", hour, minutes, cha); 51 | 52 | 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1027.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1027 打印沙漏 (20 分) 3 | 4 | 本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印 5 | 6 | ***** 7 | *** 8 | * 9 | *** 10 | ***** 11 | 12 | 所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。 13 | 14 | 给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。 15 | 输入格式: 16 | 17 | 输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。 18 | 输出格式: 19 | 20 | 首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。 21 | 输入样例: 22 | 23 | 19 * 24 | 25 | 输出样例: 26 | 27 | ***** 28 | *** 29 | * 30 | *** 31 | ***** 32 | 2 33 | 34 | */ 35 | 36 | #include 37 | #include 38 | #include 39 | 40 | int main () 41 | { 42 | int number, count, leave; 43 | char c; 44 | 45 | int i, j; 46 | 47 | if (!scanf("%d %c", &number, &c)) { 48 | return 1; 49 | } 50 | 51 | count = sqrt((number + 1) / 2); 52 | 53 | leave = number - (2 * count * count - 1); 54 | 55 | for (i = count; i > 0; i--) { 56 | for (j = 0; j < count - i; j++) { 57 | printf(" "); 58 | } 59 | for (j = 0; j < 2*i - 1; j++) { 60 | printf("%c", c); 61 | } 62 | printf("\n"); 63 | 64 | } 65 | for (i = 2; i <= count; i++) { 66 | for (j = 0; j < count - i; j++) { 67 | printf(" "); 68 | } 69 | for (j = 0; j < 2*i - 1; j++) { 70 | printf("%c", c); 71 | } 72 | printf("\n"); 73 | } 74 | 75 | 76 | printf("%d\n", leave); 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1086.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1086 就不告诉你(15 分) 3 | 4 | 做作业的时候,邻座的小盆友问你:“五乘以七等于多少?”你应该不失礼貌地围笑着告诉他:“五十三。”本题就要求你,对任何一对给定的正整数,倒着输出它们的乘积。 5 | 6 | 53.jpg 7 | 输入格式: 8 | 9 | 输入在第一行给出两个不超过 1000 的正整数 A 和 B,其间以空格分隔。 10 | 输出格式: 11 | 12 | 在一行中倒着输出 A 和 B 的乘积。 13 | 输入样例: 14 | 15 | 5 7 16 | 17 | 输出样例: 18 | 19 | 53 20 | 21 | 作者: CHEN, Yue 22 | 单位: 浙江大学 23 | 时间限制: 400 ms 24 | 内存限制: 64 MB 25 | 代码长度限制: 16 KB 26 | */ 27 | 28 | #include 29 | #include 30 | 31 | int main () 32 | { 33 | int x, y; 34 | int n, yu; 35 | int flag = 0; 36 | 37 | if (!scanf("%d %d", &x, &y)) { 38 | return 1; 39 | } 40 | 41 | n = x * y; 42 | 43 | while (n != 0) { 44 | yu = n % 10; 45 | 46 | if (yu == 0) { 47 | if (flag) { 48 | printf("%d", yu); 49 | } 50 | } else { 51 | flag = 1; 52 | printf("%d", yu); 53 | } 54 | 55 | n = n / 10; 56 | } 57 | 58 | return 0; 59 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1087.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1087 有多少不同的值(20 分) 3 | 4 | 当自然数 n 依次取 1、2、3、……、N 时,算式 ⌊n/2⌋+⌊n/3⌋+⌊n/5⌋ 有多少个不同的值?(注:⌊x⌋ 为取整函数,表示不超过 x 的最大自然数,即 x 的整数部分。) 5 | 输入格式: 6 | 7 | 输入给出一个正整数 N(2≤N≤10​4​​)。 8 | 输出格式: 9 | 10 | 在一行中输出题面中算式取到的不同值的个数。 11 | 输入样例: 12 | 13 | 2017 14 | 15 | 输出样例: 16 | 17 | 1480 18 | 19 | */ 20 | #include 21 | #include 22 | #include 23 | 24 | int main () 25 | { 26 | int number, tmp = 0; 27 | int result[10001]; 28 | int cnt = 0, i, j, flag = 0; 29 | 30 | if (!scanf("%d", &number)) { 31 | return 1; 32 | } 33 | 34 | for (i = 1; i <= number; i++) { 35 | tmp = floor(i/2) + floor(i/3) + floor(i/5); 36 | flag = 0; 37 | for (j = 0; j < cnt; j++) { 38 | if (result[j] == tmp) { 39 | flag = 1; 40 | break; 41 | } 42 | } 43 | 44 | if (flag) { 45 | continue; 46 | } else { 47 | result[cnt++] = tmp; 48 | } 49 | } 50 | 51 | 52 | printf("%d", cnt); 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1088.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1088 三人行(20 分) 3 | 4 | 子曰:“三人行,必有我师焉。择其善者而从之,其不善者而改之。” 5 | 6 | 本题给定甲、乙、丙三个人的能力值关系为:甲的能力值确定是 2 位正整数;把甲的能力值的 2 个数字调换位置就是乙的能力值;甲乙两人能力差是丙的能力值的 X 倍;乙的能力值是丙的 Y 倍。请你指出谁比你强应“从之”,谁比你弱应“改之”。 7 | 输入格式: 8 | 9 | 输入在一行中给出三个数,依次为:M(你自己的能力值)、X 和 Y。三个数字均为不超过 1000 的正整数。 10 | 输出格式: 11 | 12 | 在一行中首先输出甲的能力值,随后依次输出甲、乙、丙三人与你的关系:如果其比你强,输出 Cong;平等则输出 Ping;比你弱则输出 Gai。其间以 1 个空格分隔,行首尾不得有多余空格。 13 | 14 | 注意:如果解不唯一,则以甲的最大解为准进行判断;如果解不存在,则输出 No Solution。 15 | 输入样例 1: 16 | 17 | 48 3 7 18 | 19 | 输出样例 1: 20 | 21 | 48 Ping Cong Gai 22 | 23 | 输入样例 2: 24 | 25 | 48 11 6 26 | 27 | 输出样例 2: 28 | 29 | No Solution 30 | 31 | 注意浮点运算 32 | */ 33 | #include 34 | #include 35 | #include 36 | 37 | int m_r(int a); 38 | char *m_cmp(float my, float ot); 39 | 40 | int main () 41 | { 42 | float my, x, y; 43 | 44 | int min = 10, max = 99; 45 | 46 | int i, flag = 0; 47 | 48 | float jia, yi, bing, cha; 49 | 50 | if (!scanf("%f %f %f", &my, &x, &y)) { 51 | return 1; 52 | } 53 | 54 | for (i = max; i >= min; i--) { 55 | jia = i; 56 | yi = m_r(jia); 57 | 58 | if (jia > yi) { 59 | cha = jia - yi; 60 | } else { 61 | cha = yi - jia; 62 | } 63 | 64 | 65 | bing = cha / x; 66 | if (bing * y == yi) { 67 | flag = 1; 68 | break; 69 | } 70 | 71 | } 72 | 73 | if (flag) { 74 | printf("%.0f %s %s %s", jia, m_cmp(my, jia), m_cmp(my, yi), m_cmp(my, bing)); 75 | } else { 76 | printf("No Solution"); 77 | } 78 | return 0; 79 | } 80 | 81 | int m_r(int a) 82 | { 83 | int sum = 0; 84 | 85 | sum = a % 10 * 10 + a / 10; 86 | 87 | return sum; 88 | } 89 | 90 | char *m_cmp(float my, float ot) 91 | { 92 | char *s; 93 | s = (char *)malloc(6); 94 | 95 | if (ot > my) { 96 | strcpy(s, "Cong"); 97 | } else if (ot < my) { 98 | strcpy(s, "Gai"); 99 | } else { 100 | strcpy(s, "Ping"); 101 | } 102 | 103 | return s; 104 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1089.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1089 狼人杀-简单版(20 分) 3 | 4 | 以下文字摘自《灵机一动·好玩的数学》:“狼人杀”游戏分为狼人、好人两大阵营。在一局“狼人杀”游戏中,1 号玩家说:“2 号是狼人”,2 号玩家说:“3 号是好人”,3 号玩家说:“4 号是狼人”,4 号玩家说:“5 号是好人”,5 号玩家说:“4 号是好人”。已知这 5 名玩家中有 2 人扮演狼人角色,有 2 人说的不是实话,有狼人撒谎但并不是所有狼人都在撒谎。扮演狼人角色的是哪两号玩家? 5 | 6 | 本题是这个问题的升级版:已知 N 名玩家中有 2 人扮演狼人角色,有 2 人说的不是实话,有狼人撒谎但并不是所有狼人都在撒谎。要求你找出扮演狼人角色的是哪几号玩家? 7 | 输入格式: 8 | 9 | 输入在第一行中给出一个正整数 N(5≤N≤100)。随后 N 行,第 i 行给出第 i 号玩家说的话(1≤i≤N),即一个玩家编号,用正号表示好人,负号表示狼人。 10 | 输出格式: 11 | 12 | 如果有解,在一行中按递增顺序输出 2 个狼人的编号,其间以空格分隔,行首尾不得有多余空格。如果解不唯一,则输出最小序列解 —— 即对于两个序列 A=a[1],...,a[M] 和 B=b[1],...,b[M],若存在 0≤k 55 | #include 56 | 57 | int main () 58 | { 59 | int num = 0, tmp[100], h_num = 0, l_h = 0; 60 | int i, j, z; 61 | 62 | if (!scanf("%d", &num)) { 63 | return 1; 64 | } 65 | 66 | for (i = 0; i < num; i++) { 67 | if (!scanf("%d", &tmp[i])) { 68 | return 1; 69 | } 70 | } 71 | //假设有两个是狼人,计算说谎人数,等于2说明符合 72 | for (i = 0; i < (num - 1); i++) { 73 | for (j = (i + 1); j < num; j++) { 74 | h_num = 0; 75 | l_h = 0; 76 | for (z = 0; z < num; z++) { 77 | if (tmp[z] > 0) { 78 | if (tmp[z] == (i + 1) || tmp[z] == (j + 1)) { 79 | if (z == i || z == j) { 80 | l_h++; 81 | } 82 | h_num++; 83 | } 84 | } else if (tmp[z] < 0) { 85 | if (tmp[z] != -(i + 1) && tmp[z] != -(j + 1)) { 86 | if (z == i || z == j) { 87 | l_h++; 88 | } 89 | h_num++; 90 | } 91 | } 92 | } 93 | 94 | if (h_num == 2 && l_h == 1) { 95 | printf("%d %d", i + 1, j + 1); 96 | break; 97 | } 98 | } 99 | if (h_num == 2 && l_h == 1) { 100 | break; 101 | } 102 | } 103 | 104 | if (h_num != 2 || l_h != 1) { 105 | printf("No Solution"); 106 | } 107 | 108 | return 0; 109 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/BasicLevel/B1090.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1090 危险品装箱(25 分) 3 | 4 | 集装箱运输货物时,我们必须特别小心,不能把不相容的货物装在一只箱子里。比如氧化剂绝对不能跟易燃液体同箱,否则很容易造成爆炸。 5 | 6 | 本题给定一张不相容物品的清单,需要你检查每一张集装箱货品清单,判断它们是否能装在同一只箱子里。 7 | 输入格式: 8 | 9 | 输入第一行给出两个正整数:N (≤10​4​​) 是成对的不相容物品的对数;M (≤100) 是集装箱货品清单的单数。 10 | 11 | 随后数据分两大块给出。第一块有 N 行,每行给出一对不相容的物品。第二块有 M 行,每行给出一箱货物的清单,格式如下: 12 | 13 | K G[1] G[2] ... G[K] 14 | 15 | 其中 K (≤1000) 是物品件数,G[i] 是物品的编号。简单起见,每件物品用一个 5 位数的编号代表。两个数字之间用空格分隔。 16 | 输出格式: 17 | 18 | 对每箱货物清单,判断是否可以安全运输。如果没有不相容物品,则在一行中输出 Yes,否则输出 No。 19 | 输入样例: 20 | 21 | 6 3 22 | 20001 20002 23 | 20003 20004 24 | 20005 20006 25 | 20003 20001 26 | 20005 20004 27 | 20004 20006 28 | 4 00001 20004 00002 20003 29 | 5 98823 20002 20003 20006 10010 30 | 3 12345 67890 23333 31 | 32 | 输出样例: 33 | 34 | No 35 | Yes 36 | Yes 37 | 38 | 使用快速排序和二分查找,减少程序运行时间. 39 | */ 40 | 41 | #include 42 | #include 43 | 44 | int m_cmp(const void *p, const void *q); 45 | 46 | int main () 47 | { 48 | int dui_n = 0, dan_n = 0, num_n[100]; 49 | int dui[10000][2]; 50 | int dan[100][1000]; 51 | 52 | int i, j, flag = 0; 53 | 54 | if (!scanf("%d %d", &dui_n, &dan_n)) { 55 | return 1; 56 | } 57 | 58 | for (i = 0; i < dui_n; i++) { 59 | if (!scanf("%d %d", &dui[i][0], &dui[i][1])) { 60 | return 1; 61 | } 62 | } 63 | 64 | for (i = 0; i < dan_n; i++) { 65 | if (!scanf("%d", &num_n[i])) { 66 | return 1; 67 | } 68 | for (j = 0; j < num_n[i]; j++) { 69 | if (!scanf("%d", &dan[i][j])) { 70 | return 1; 71 | } 72 | } 73 | qsort(dan[i], num_n[i], sizeof(int), m_cmp); 74 | } 75 | 76 | for (j = 0; j < dan_n; j++) { 77 | flag = 0; 78 | for (i = 0; i < dui_n; i++) { 79 | if ((int *)bsearch(&dui[i][0], dan[j], num_n[j], sizeof(int), m_cmp) != NULL && (int *)bsearch(&dui[i][1], dan[j], num_n[j], sizeof(int), m_cmp) != NULL) { 80 | flag = 1; 81 | break; 82 | } 83 | } 84 | if (flag) { 85 | printf("No\n"); 86 | } else { 87 | printf("Yes\n"); 88 | } 89 | } 90 | return 0; 91 | } 92 | 93 | int m_cmp(const void *p, const void *q) 94 | { 95 | int a = *(int *)p; 96 | int b = *(int *)q; 97 | return a - b; 98 | } -------------------------------------------------------------------------------- /C/PatQuestionBank/README.md: -------------------------------------------------------------------------------- 1 | ##### PAT程序设计题库 https://www.patest.cn/practice -------------------------------------------------------------------------------- /C/PatQuestionBank/TopLevel/README.md: -------------------------------------------------------------------------------- 1 | #### 未进行 -------------------------------------------------------------------------------- /C/README.md: -------------------------------------------------------------------------------- 1 | #### 一些c语言代码片段 2 | 3 | #### **已迁移至 [graffito-c](https://github.com/2lovecode/graffito-c)** 4 | 5 | - Calculator : 计算器实现 6 | - DataStructureAndAlgorithm : 数据结构和算法 7 | - DictOrder : 字典序问题 8 | - Queue : 队列实现 9 | - Stack : 栈实现 10 | - GetLineOperation : 读取标准输入 11 | - PatQuestionBank : PAT能力考试真题题库解答 https://www.patest.cn/practice 12 | - SwapValue : 值交换 13 | -------------------------------------------------------------------------------- /C/RedisSourceCodeDemo/README.md: -------------------------------------------------------------------------------- 1 | #### 仿照redis源代码写的一些简单的实现示例,帮助理解redis源码 -------------------------------------------------------------------------------- /C/RedisSourceCodeDemo/Sds/README.md: -------------------------------------------------------------------------------- 1 | #### redis中简单动态字符串SDS的实现示例 2 | 3 | ##### sds.c是定义 test.c是测试 4 | ##### 环境: Linux 5 | ##### 编译: gcc test.c -o test 6 | ##### 执行: ./test -------------------------------------------------------------------------------- /C/RedisSourceCodeDemo/Sds/test: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/C/RedisSourceCodeDemo/Sds/test -------------------------------------------------------------------------------- /C/RedisSourceCodeDemo/Sds/test.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "sds.c" 4 | 5 | void main () { 6 | char *str = "Hello World!"; 7 | sds s = createSDS(str, strlen(str)); 8 | printf("测试字符串:%s\n", s); 9 | printf("长度Len为:%ld\n", getSDSLen(s)); 10 | printf("容量Cap为:%ld\n", getSDSCap(s)); 11 | } -------------------------------------------------------------------------------- /C/SwapValue/SwapValue.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) 4 | { 5 | printf("%p, %p\n", a, b); 6 | *a = *a ^ *b; 7 | *b = *a ^ *b; 8 | *a = *b ^ *a; 9 | } 10 | 11 | void main() 12 | { 13 | int a = 3; 14 | int b = 2; 15 | 16 | printf("%d, %d\n", a, b); 17 | 18 | swap(&a, &b); 19 | 20 | printf("%d, %d\n", a, b); 21 | 22 | } -------------------------------------------------------------------------------- /Css/.gitignore: -------------------------------------------------------------------------------- 1 | Assets -------------------------------------------------------------------------------- /Css/Elephant/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 纯CSS3实现大象走路动画DEMO演示 8 | 9 | 10 | 11 | 12 | 13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | 41 | -------------------------------------------------------------------------------- /Css/Snow/pics/snow-b.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/Css/Snow/pics/snow-b.png -------------------------------------------------------------------------------- /Css/Snow/pics/snow-f.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/Css/Snow/pics/snow-f.png -------------------------------------------------------------------------------- /Css/Snow/pics/snow-m.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/Css/Snow/pics/snow-m.png -------------------------------------------------------------------------------- /Go/GoLearn.md: -------------------------------------------------------------------------------- 1 | #### Golang学习资料 2 | 3 | ### Plan9汇编入门 4 | - [go和plan9 汇编](https://xargin.com/go-and-plan9-asm/) 5 | - [plan9 汇编入门](https://xargin.com/plan9-assembly/) 6 | - [go夜读-plan9-视频](https://www.bilibili.com/video/BV1Xb411J7Yk) 7 | - [go夜读-plan9-文档](https://github.com/cch123/asmshare) 8 | 9 | ### 调度器(GMP模型) 10 | - [Golang的协程调度器原理及GMP设计思想{blog}](https://github.com/aceld/golang/blob/main/2%E3%80%81Golang%E7%9A%84%E5%8D%8F%E7%A8%8B%E8%B0%83%E5%BA%A6%E5%99%A8%E5%8E%9F%E7%90%86%E5%8F%8AGMP%E8%AE%BE%E8%AE%A1%E6%80%9D%E6%83%B3%EF%BC%9F.md) 11 | - [Golang深入理解GPM模型{video}](https://www.bilibili.com/video/BV19r4y1w7Nx?spm_id_from=333.999.0.0) -------------------------------------------------------------------------------- /Go/Image2Base64/README.md: -------------------------------------------------------------------------------- 1 | # Image2Base64std 2 | use go walk gui to make a window exe 3 | -------------------------------------------------------------------------------- /Go/Image2Base64/go.mod: -------------------------------------------------------------------------------- 1 | module image2base64 2 | 3 | go 1.16 4 | 5 | require fyne.io/fyne/v2 v2.1.2 6 | -------------------------------------------------------------------------------- /Go/Image2Base64/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | // b64 "encoding/base64" 5 | 6 | "fyne.io/fyne/v2/app" 7 | "fyne.io/fyne/v2/widget" 8 | ) 9 | 10 | func main() { 11 | a := app.New() 12 | w := a.NewWindow("Hello World") 13 | // uEnc := b64.StdEncoding.EncodeToString(buf) 14 | w.SetContent(widget.NewLabel("Hello World!")) 15 | w.ShowAndRun() 16 | } 17 | -------------------------------------------------------------------------------- /Go/LearnDemo/PrintBigDigits/PrintBigDigits.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | ) 7 | 8 | var bigDigits = [][]string{ 9 | { 10 | " 000 ", 11 | " 0 0 ", 12 | "0 0", 13 | "0 0", 14 | "0 0", 15 | " 0 0 ", 16 | " 000 ", 17 | }, 18 | { 19 | " 1 ", 20 | "11 ", 21 | " 1 ", 22 | " 1 ", 23 | " 1 ", 24 | " 1 ", 25 | "111", 26 | }, 27 | { 28 | " 222 ", 29 | "2 2", 30 | " 2", 31 | " 2 ", 32 | " 2 ", 33 | "2 ", 34 | "22222", 35 | }, 36 | { 37 | " 333 ", 38 | "3 3", 39 | " 3", 40 | " 33 ", 41 | " 3", 42 | "3 3", 43 | " 333 ", 44 | }, 45 | { 46 | " 4 ", 47 | " 44 ", 48 | " 4 4 ", 49 | "4 4 ", 50 | " 444444", 51 | " 4 ", 52 | " 4 ", 53 | }, 54 | { 55 | "55555", 56 | "5 ", 57 | "5 ", 58 | "555 ", 59 | " 5", 60 | "5 5", 61 | "555 ", 62 | }, 63 | { 64 | "6666 ", 65 | "6 ", 66 | "6 ", 67 | "6666 ", 68 | "6 6", 69 | "6 6", 70 | "6666 ", 71 | }, 72 | { 73 | "77777 ", 74 | " 7", 75 | " 7 ", 76 | " 7 ", 77 | " 7 ", 78 | " 7 ", 79 | "7 ", 80 | }, 81 | { 82 | " 888 ", 83 | "8 8", 84 | "8 8", 85 | " 888 ", 86 | "8 8", 87 | "8 8", 88 | " 888 ", 89 | }, 90 | { 91 | " 9999", 92 | "9 9", 93 | "9 9", 94 | " 9999", 95 | " 9", 96 | " 9", 97 | " 9999", 98 | }, 99 | } 100 | 101 | func main() { 102 | if len(os.Args) == 1 { 103 | os.Exit(1) 104 | } 105 | stringOfDigits := os.Args[1] 106 | for row := range bigDigits[0] { 107 | line := "" 108 | for number := range stringOfDigits { 109 | numberIndex := stringOfDigits[number] - '0' 110 | line += bigDigits[numberIndex][row] + " " 111 | } 112 | fmt.Println(line) 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /Go/LearnDemo/PrintBigDigits/README.md: -------------------------------------------------------------------------------- 1 | #### 2 | 3 | -------------------------------------------------------------------------------- /Go/README.md: -------------------------------------------------------------------------------- 1 | #### Go语言示例 2 | #### **已迁移至 [graffito](https://github.com/2lovecode/graffito)** 3 | 4 | - Timer : 基于redis zset list 实现的定时器. -------------------------------------------------------------------------------- /JavaScript/Demo/DemoOne/changeValue.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | change value 6 | 7 | 8 | 16 | 17 | 18 |
19 | 我喜欢 20 |
21 |
22 | 我不喜欢 23 |
24 | 25 | 26 | -------------------------------------------------------------------------------- /JavaScript/Demo/DemoOne/validateInputValue.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | validate input value 6 | 7 | 8 | 9 | 10 |
11 | 14 | 15 |
16 | 19 | 20 |
21 | 22 |
23 | 26 |
27 | 28 | 29 | -------------------------------------------------------------------------------- /JavaScript/Demo/DemoTwo/Demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | Document 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /JavaScript/README.md: -------------------------------------------------------------------------------- 1 | #### JavaScript代码 2 | 3 | - TencentMapApi : 腾讯地图api示例 4 | - Tools : 一些自己写的实用工具集合[序列化 反序列化 手机IMEI生成器] -------------------------------------------------------------------------------- /JavaScript/TencentMapApi/TencentMapApi.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Tencent Map Api 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 76 | 77 | -------------------------------------------------------------------------------- /JavaScript/Tools/Assets/utf.js: -------------------------------------------------------------------------------- 1 | /* utf.js - UTF-8 <=> UTF-16 convertion 2 | * 3 | * Copyright (C) 2010 zys 4 | * Version: 1.0 5 | * LastModified: Six 3, 2010 6 | * This library is free. You can redistribute it and/or modify it. 7 | */ 8 | 9 | /* 10 | * Interfaces: 11 | * utf8 = utf16to8(utf16); 12 | * utf16 = utf16to8(utf8); 13 | */ 14 | 15 | function utf16to8(str) { 16 | var out, i, len, c; 17 | 18 | out = ""; 19 | len = str.length; 20 | for (i = 0; i < len; i++) { 21 | c = str.charCodeAt(i); 22 | if ((c >= 0x0001) && (c <= 0x007F)) { 23 | out += str.charAt(i); 24 | } else if (c > 0x07FF) { 25 | out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F)); 26 | out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F)); 27 | out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); 28 | } else { 29 | out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F)); 30 | out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F)); 31 | } 32 | } 33 | return out; 34 | } 35 | 36 | function utf8to16(str) { 37 | var out, i, len, c; 38 | var char2, char3; 39 | 40 | out = ""; 41 | len = str.length; 42 | i = 0; 43 | while (i < len) { 44 | c = str.charCodeAt(i++); 45 | switch (c >> 4) { 46 | case 0: 47 | case 1: 48 | case 2: 49 | case 3: 50 | case 4: 51 | case 5: 52 | case 6: 53 | case 7: 54 | // 0xxxxxxx 55 | out += str.charAt(i - 1); 56 | break; 57 | case 12: 58 | case 13: 59 | // 110x xxxx 10xx xxxx 60 | char2 = str.charCodeAt(i++); 61 | out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); 62 | break; 63 | case 14: 64 | // 1110 xxxx 10xx xxxx 10xx xxxx 65 | char2 = str.charCodeAt(i++); 66 | char3 = str.charCodeAt(i++); 67 | out += String.fromCharCode(((c & 0x0F) << 12) | 68 | ((char2 & 0x3F) << 6) | 69 | ((char3 & 0x3F) << 0)); 70 | break; 71 | } 72 | } 73 | 74 | return out; 75 | } -------------------------------------------------------------------------------- /JavaScript/Tools/Serialization/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 反序列化 9 | 28 | 29 | 30 | 31 | 32 |
33 |

34 | 序列化 35 | 36 | 37 | 首页 38 | 39 | 40 |

41 |
42 |
43 |

44 | 45 |

46 |

47 | 48 |

49 |

50 | 51 |

52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /JavaScript/Tools/Unserialization/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 反序列化 9 | 28 | 29 | 30 | 31 | 32 |
33 |

34 | 反序列化 35 | 36 | 37 | 首页 38 | 39 | 40 |

41 |
42 |
43 |

44 | 45 |

46 |

47 | 48 |

49 |

50 | 51 |

52 |
53 | 54 | 55 | -------------------------------------------------------------------------------- /JavaScript/Tools/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 7 | 8 | 工具集 9 | 35 | 36 | 37 |
38 |

39 | 实用工具集合 40 |

41 |
42 |
43 | 54 |
55 | 56 | -------------------------------------------------------------------------------- /Php/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor/ -------------------------------------------------------------------------------- /Php/Container/ContextualBindingBuilder.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | require_once 'ContextualBindingBuilderInterface.php'; 9 | 10 | class ContextualBindingBuilder implements ContextualBindingBuilderInterface 11 | { 12 | protected $container; 13 | 14 | protected $concrete; 15 | 16 | protected $needs; 17 | 18 | public function __construct(OContainer $container, $concrete) 19 | { 20 | $this->concrete = $concrete; 21 | $this->container = $container; 22 | } 23 | 24 | public function needs($abstract) 25 | { 26 | $this->needs = $abstract; 27 | 28 | return $this; 29 | } 30 | 31 | public function give($implementation) 32 | { 33 | $this->container->addContextualBinding( 34 | $this->concrete, $this->needs, $implementation 35 | ); 36 | } 37 | } -------------------------------------------------------------------------------- /Php/Container/ContextualBindingBuilderInterface.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | interface ContextualBindingBuilderInterface 10 | { 11 | public function needs($abstract); 12 | 13 | public function give($implementation); 14 | } -------------------------------------------------------------------------------- /Php/Container/Examples/ContainerEvent.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 9 | * 容器事件 10 | */ 11 | 12 | require_once '../OContainer.php'; 13 | 14 | interface Ei 15 | { 16 | public function run(); 17 | } 18 | 19 | class Ei01 implements Ei 20 | { 21 | public function run() 22 | { 23 | } 24 | } 25 | 26 | class Ei02 implements Ei 27 | { 28 | public function run() 29 | { 30 | } 31 | } 32 | /************************** 容器事件 ********************************/ 33 | 34 | $container = new OContainer(); 35 | 36 | //绑定全局容器事件 37 | $container->resolving(function () { 38 | echo 'Global Resolving!'; 39 | }); 40 | 41 | //绑定局部容器事件 42 | $container->resolving('Ei02', function () { 43 | echo 'Ei02 Resolving'; 44 | }); 45 | 46 | //获取实例 47 | $container->make('Ei01'); 48 | echo '
'; 49 | $container->make('Ei02'); -------------------------------------------------------------------------------- /Php/Container/Examples/ContextBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 上下文绑定 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Ef 14 | { 15 | public function run(); 16 | } 17 | 18 | class Ef01 implements Ef 19 | { 20 | public function run() 21 | { 22 | echo "I am Ef01!"; 23 | } 24 | } 25 | 26 | class Ef02 implements Ef 27 | { 28 | public function run() 29 | { 30 | echo "I am Ef02!"; 31 | } 32 | } 33 | 34 | interface Of 35 | { 36 | public function __construct(Ef $e); 37 | 38 | public function run(); 39 | } 40 | 41 | class Of01 42 | { 43 | private $e; 44 | 45 | public function __construct(Ef $e) 46 | { 47 | $this->e = $e; 48 | } 49 | 50 | public function run() 51 | { 52 | echo $this->e->run(); 53 | } 54 | } 55 | 56 | class Of02 57 | { 58 | private $e; 59 | 60 | public function __construct(Ef $e) 61 | { 62 | $this->e = $e; 63 | } 64 | 65 | public function run() 66 | { 67 | echo $this->e->run(); 68 | } 69 | } 70 | 71 | /************************** 上下文绑定 ********************************/ 72 | 73 | $container = new OContainer(); 74 | 75 | //绑定 76 | $container->when('Of01')->needs('Ef')->give('Ef01'); 77 | $container->when('Of02')->needs('Ef')->give('Ef02'); 78 | 79 | //获取实例 80 | $of01 = $container->make('Of01'); 81 | $of02 = $container->make('Of02'); 82 | 83 | $of01->run(); 84 | $of02->run(); -------------------------------------------------------------------------------- /Php/Container/Examples/ExtendBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 扩展绑定 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Eh 14 | { 15 | public function run(); 16 | } 17 | 18 | class EhBase implements Eh 19 | { 20 | public function run() 21 | { 22 | echo "<----Base---->"; 23 | } 24 | } 25 | 26 | class EhBaseDecorator extends EhBase 27 | { 28 | private $base; 29 | 30 | public function __construct(Eh $base) 31 | { 32 | $this->base = $base; 33 | } 34 | 35 | public function getBase() 36 | { 37 | return $this->base; 38 | } 39 | } 40 | class RedEhBase extends EhBaseDecorator 41 | { 42 | public function run() 43 | { 44 | echo "<----Red---->"; 45 | $this->getBase()->run(); 46 | } 47 | } 48 | 49 | class BigEhBase extends EhBaseDecorator 50 | { 51 | public function run() 52 | { 53 | echo "<----Big---->"; 54 | $this->getBase()->run(); 55 | } 56 | } 57 | 58 | /************************** 扩展绑定示例 ********************************/ 59 | 60 | $container = new OContainer(); 61 | 62 | $ehBase = $container->make('EhBase'); 63 | $ehBase->run(); 64 | 65 | echo '
'; 66 | //绑定 67 | $container->extend('EhBase', function ($ehBase) { 68 | return new BigEhBase(new RedEhBase($ehBase)); 69 | }); 70 | 71 | //获取实例 72 | $bigRedEhBase = $container->make('EhBase'); 73 | $bigRedEhBase->run(); -------------------------------------------------------------------------------- /Php/Container/Examples/ImplementToInterface.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 绑定实现到接口 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Ee 14 | { 15 | public function run(); 16 | } 17 | 18 | class Ee01 implements Ee 19 | { 20 | public function run() 21 | { 22 | echo "I am Ee01!"; 23 | } 24 | } 25 | 26 | class O 27 | { 28 | private $e; 29 | 30 | public function __construct(Ee $e) 31 | { 32 | $this->e = $e; 33 | } 34 | 35 | public function run() 36 | { 37 | $this->e->run(); 38 | } 39 | } 40 | 41 | /************************** 绑定实现到接口 ********************************/ 42 | 43 | $container = new OContainer(); 44 | 45 | //绑定 46 | $container->bind('Ee', 'Ee01'); 47 | 48 | //获取实例 49 | $o = $container->make('O'); 50 | $o->run(); 51 | -------------------------------------------------------------------------------- /Php/Container/Examples/InitalDataBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 绑定初始数据 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Ed 14 | { 15 | public function __construct($params); 16 | } 17 | 18 | class Ed01 implements Ed 19 | { 20 | private $params; 21 | 22 | public function __construct($params) 23 | { 24 | $this->params = $params; 25 | } 26 | 27 | public function run() 28 | { 29 | echo $this->params; 30 | } 31 | } 32 | 33 | /************************** 绑定初始数据 ********************************/ 34 | 35 | $container = new OContainer(); 36 | 37 | $value = 'Hello World!'; 38 | 39 | //绑定, $符号不能丢 40 | $container->when('Ed01')->needs('$params')->give($value); 41 | 42 | //获取实例 43 | $ed01 = $container->make('Ed01'); 44 | 45 | $ed01->run(); -------------------------------------------------------------------------------- /Php/Container/Examples/InstanceBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 绑定一个实例 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Ec 14 | { 15 | public function run(); 16 | } 17 | 18 | class Ec01 implements Ec 19 | { 20 | public function run() 21 | { 22 | return 'I am Ec01'; 23 | } 24 | } 25 | 26 | /************************** 绑定一个单例示例 ********************************/ 27 | 28 | $container = new OContainer(); 29 | 30 | $ec01 = new Ec01(); 31 | 32 | //绑定 33 | $container->instance('Ec', $ec01); 34 | 35 | //获取实例 36 | $ec0101 = $container->make('Ec'); 37 | 38 | var_dump($ec0101->run()); -------------------------------------------------------------------------------- /Php/Container/Examples/SimpleBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 9 | * 简单绑定示例 10 | */ 11 | 12 | require_once '../OContainer.php'; 13 | 14 | class E 15 | { 16 | public function run() 17 | { 18 | echo "I am E;"; 19 | } 20 | } 21 | 22 | interface Ea 23 | { 24 | public function __construct(E $e); 25 | } 26 | 27 | class Ea01 implements Ea 28 | { 29 | /** 30 | * @var E 31 | */ 32 | private $e; 33 | 34 | public function __construct(E $e) 35 | { 36 | $this->e = $e; 37 | } 38 | 39 | public function run() 40 | { 41 | $this->e->run(); 42 | } 43 | } 44 | 45 | /************************** 简单绑定示例 ********************************/ 46 | 47 | $container = new OContainer(); 48 | 49 | //绑定 50 | $container->bind('Ea', function (OContainerInterface $container) { 51 | return new Ea01($container->make('E')); 52 | }); 53 | 54 | //获取实例 55 | $ea01 = $container->make('Ea'); 56 | 57 | $ea01->run(); 58 | -------------------------------------------------------------------------------- /Php/Container/Examples/SingletonBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 绑定一个单例 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Eb 14 | { 15 | public function run(); 16 | } 17 | 18 | class Eb01 implements Eb 19 | { 20 | private $sum = 0; 21 | 22 | public function run() 23 | { 24 | return ++$this->sum; 25 | } 26 | } 27 | 28 | /************************** 绑定一个单例示例 ********************************/ 29 | 30 | $container = new OContainer(); 31 | 32 | //绑定 33 | $container->singleton('Eb', function (OContainerInterface $container) { 34 | return new Eb01(); 35 | }); 36 | 37 | //获取实例 38 | $eb0101 = $container->make('Eb'); 39 | 40 | var_dump($eb0101->run()); 41 | 42 | $eb0102 = $container->make('Eb'); 43 | var_dump($eb0102->run()); -------------------------------------------------------------------------------- /Php/Container/Examples/TagBind.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 标记绑定 9 | */ 10 | 11 | require_once '../OContainer.php'; 12 | 13 | interface Eg 14 | { 15 | public function run(); 16 | } 17 | 18 | class Eg01 implements Eg 19 | { 20 | public function run() 21 | { 22 | echo "I am Eg01!"; 23 | } 24 | } 25 | 26 | class Eg02 implements Eg 27 | { 28 | public function run() 29 | { 30 | echo "I am Eg02!"; 31 | } 32 | } 33 | 34 | class Eg03 implements Eg 35 | { 36 | public function run() 37 | { 38 | echo "I am Eg03!"; 39 | } 40 | } 41 | 42 | /************************** 标记绑定 ********************************/ 43 | 44 | $container = new OContainer(); 45 | 46 | //绑定 47 | $container->bind('Eg01', 'Eg01'); 48 | $container->bind('Eg02', 'Eg02'); 49 | $container->bind('Eg03', 'Eg03'); 50 | 51 | $container->tag(['Eg01', 'Eg02', 'Eg03'], 'Ege'); 52 | 53 | //获取实例 54 | $aggregator = $container->tagged('Ege'); 55 | 56 | foreach ($aggregator as $each) { 57 | $each->run(); 58 | } -------------------------------------------------------------------------------- /Php/Container/OContainerInterface.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | interface OContainerInterface 10 | { 11 | public function bound($abstract); 12 | 13 | public function alias($abstract, $alias); 14 | 15 | public function tag($abstracts, $tags); 16 | 17 | public function tagged($tag); 18 | 19 | public function bind($abstract, $concrete = null, $shared = false); 20 | 21 | public function bindIf($abstract, $concrete = null, $shared = false); 22 | 23 | public function singleton($abstract, $concrete = null); 24 | 25 | public function extend($abstract, Closure $closure); 26 | 27 | public function instance($abstract, $instance); 28 | 29 | public function when($concrete); 30 | 31 | public function factory($abstract); 32 | 33 | public function make($abstract, array $parameters = []); 34 | 35 | public function call($callback, array $parameters = [], $defaultMethod = null); 36 | 37 | public function resolved($abstract); 38 | 39 | public function resolving($abstract, Closure $callback = null); 40 | 41 | public function afterResolving($abstract, Closure $callback = null); 42 | } -------------------------------------------------------------------------------- /Php/Container/README.md: -------------------------------------------------------------------------------- 1 | #### 依赖注入容器(DI)的实现, 借鉴自laravel框架 2 | 3 | 1. ContextualBindingBuilderInterface 4 | 2. ContextualBindingBuilder 5 | 3. OContainerInterface 6 | 4. OContainer 7 | 8 | 分别是摘自laravel框架的容器实现类 9 | 10 | #### 示例 11 | 12 | Examples 文件夹中是容器的使用示例 -------------------------------------------------------------------------------- /Php/DataStructureAndAlgorithm/Hash/HashToImplementArray.php: -------------------------------------------------------------------------------- 1 | key = $key; 17 | $this->value = $value; 18 | $this->nextNode = $nextNode; 19 | } 20 | } 21 | class MyHashTable 22 | { 23 | private $buckets; 24 | 25 | private $size; 26 | 27 | public function __construct($size = 10) 28 | { 29 | $this->size = $size; 30 | $this->buckets = new SplFixedArray($this->size); 31 | } 32 | 33 | 34 | private function hashFunc($str) 35 | { 36 | $strLen = strlen($str); 37 | $hashValue = 0; 38 | 39 | for ($i = 0; $i < $strLen; $i++) { 40 | $hashValue += ord($str[$i]); 41 | } 42 | 43 | return $hashValue % $this->size; 44 | } 45 | 46 | 47 | public function add($key, $value) 48 | { 49 | $index = $this->hashFunc($key); 50 | 51 | if (isset($this->buckets[$index])) { 52 | $this->buckets[$index] = new HashNode($key, $value, $this->buckets[$index]); 53 | } else { 54 | $this->buckets[$index] = new HashNode($key, $value, NULL); 55 | } 56 | } 57 | 58 | public function find($key) 59 | { 60 | $index = $this->hashFunc($key); 61 | $current = $this->buckets[$index]; 62 | 63 | while ($current != NULL) { 64 | if ($current->key == $key) { 65 | break; 66 | } 67 | $current = $current->nextNode; 68 | } 69 | return $current->value; 70 | } 71 | } 72 | 73 | class Test 74 | { 75 | public function run() 76 | { 77 | $hashTable = new MyHashTable(5); 78 | 79 | $hashTable->add('abc', 123); 80 | $hashTable->add('cba', 333); 81 | 82 | var_dump($hashTable->find('abc'), $hashTable->find('cba')); 83 | } 84 | } 85 | 86 | $test = new Test(); 87 | $test->run(); -------------------------------------------------------------------------------- /Php/DataStructureAndAlgorithm/Heap/MaxHeap.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | * 8 | * 最大堆 9 | */ 10 | 11 | abstract class Heap 12 | { 13 | protected $heap = [0]; 14 | protected $size = 0; 15 | 16 | public function __construct(array $dataList = []) 17 | { 18 | foreach ($dataList as $value) { 19 | $this->size++; 20 | $this->insert($value); 21 | } 22 | } 23 | 24 | abstract public function insert($value); 25 | 26 | abstract public function delete(); 27 | 28 | public function sort() 29 | { 30 | $result = []; 31 | $size = $this->size; 32 | for ($i = 1; $i <= $size; $i++) { 33 | $result[] = $this->delete(); 34 | } 35 | return $result; 36 | } 37 | } 38 | 39 | class MaxHeap extends Heap 40 | { 41 | public function insert($value) 42 | { 43 | for ($i = $this->size; (floor($i/2) > 0) && ($this->heap[floor($i/2)] < $value); $i = floor($i/2)) { 44 | $this->heap[$i] = $this->heap[floor($i/2)]; 45 | } 46 | $this->heap[$i] = $value; 47 | } 48 | 49 | public function delete() 50 | { 51 | $maxValue = $this->heap[1]; 52 | $lastValue = $this->heap[$this->size--]; 53 | 54 | $child = 1; 55 | 56 | for ($i = 1; $i * 2 <= $this->size; $i = $child) { 57 | $child = $i * 2; 58 | $leftIndex = $child; 59 | $rightIndex = $child + 1; 60 | 61 | 62 | if (($child != $this->size) && ($this->heap[$leftIndex] < $this->heap[$rightIndex])) { 63 | $child++; 64 | } 65 | 66 | if ($this->heap[$child] > $lastValue) { 67 | $this->heap[$i] = $this->heap[$child]; 68 | } else { 69 | break; 70 | } 71 | } 72 | 73 | $this->heap[$i] = $lastValue; 74 | return $maxValue; 75 | 76 | } 77 | } 78 | 79 | $testData = [33, 4, 3, 2, 5, 6, 9, 10, 32, 23, 45, 11, 25]; 80 | $maxHeap = new MaxHeap($testData); 81 | 82 | echo '
';
83 | var_dump($maxHeap->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Heap/MinHeap.php:
--------------------------------------------------------------------------------
 1 | 
 6 |  * @copyright liu hao
 7 |  *
 8 |  * 最小堆
 9 |  */
10 | 
11 | abstract class Heap
12 | {
13 |     protected $heap = [0];
14 |     protected $size = 0;
15 | 
16 |     public function __construct(array $dataList = [])
17 |     {
18 |         foreach ($dataList as $value) {
19 |             $this->size++;
20 |             $this->insert($value);
21 |         }
22 |     }
23 | 
24 |     abstract public function insert($value);
25 | 
26 |     abstract public function delete();
27 | 
28 |     public function sort()
29 |     {
30 |         $result = [];
31 |         $size = $this->size;
32 |         for ($i = 1; $i <= $size; $i++) {
33 |             $result[] = $this->delete();
34 |         }
35 |         return $result;
36 |     }
37 | }
38 | 
39 | //最小堆
40 | class MinHeap extends Heap
41 | {
42 |     public function insert($value)
43 |     {
44 |         for ($i = $this->size; ($i > 0) && ($this->heap[floor($i/2)] > $value); $i = floor($i/2)) {
45 |             $this->heap[$i] = $this->heap[floor($i/2)];
46 |         }
47 | 
48 |         $this->heap[$i] = $value;
49 |     }
50 | 
51 | 
52 |     public function delete()
53 |     {
54 |         $minValue = $this->heap[1];
55 |         $lastValue = $this->heap[$this->size--];
56 |         $child = 1;
57 | 
58 |         for ($i = 1; $i*2 <= $this->size; $i = $child) {
59 | 
60 |             $child = $i * 2;
61 | 
62 |             $leftIndex = $child;
63 |             $rightIndex = $child + 1;
64 | 
65 |             if (($child != $this->size) && ($this->heap[$leftIndex] > $this->heap[$rightIndex])) {
66 |                 $child++;
67 |             }
68 | 
69 |             if ($lastValue > $this->heap[$child]) {
70 |                 $this->heap[$i] = $this->heap[$child];
71 |             } else {
72 |                 break;
73 |             }
74 |         }
75 | 
76 |         $this->heap[$i] = $lastValue;
77 |         return $minValue;
78 |     }
79 | }
80 | 
81 | $testData = [33, 4, 3, 2, 5, 6, 9, 10, 32, 23, 45, 11, 25];
82 | $minHeap = new MinHeap($testData);
83 | echo '
';
84 | var_dump($minHeap->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/PageRank/PageRank.php:
--------------------------------------------------------------------------------
 1 | map = $map;
18 | 		$this->size = count($this->map);
19 | 	}
20 | 
21 | 	//init rank score and transform 'map' format to 'inputList' format
22 | 	public function init()
23 | 	{
24 | 		$size = $this->size;
25 | 		foreach ($this->map as $key => $value) {
26 | 			$this->inputList[$key] = [];
27 | 		}
28 | 		foreach ($this->map as $key => $value) {
29 | 			$this->rank[$key] = 1/$size;
30 | 			foreach ($value as $v) {
31 | 				if (empty($this->inputList[$v])) {
32 | 					$this->inputList[$v][] = $key;
33 | 				} else {
34 | 					array_push($this->inputList[$v], $key);
35 | 				}
36 | 			}
37 | 			
38 | 		}
39 | 	}
40 | 
41 | 
42 | 	public function caculate()
43 | 	{
44 | 		$tmp = $this->rank;
45 | 		$keyValue = $this->keyValue;
46 | 		$size = $this->size;
47 | 
48 | 		foreach ($this->inputList as $key => $value) {
49 | 			$score = (1 - $keyValue)/$size;
50 | 			foreach ($value as $v) {
51 | 				$cc = count($this->map[$v]);
52 | 				if ($cc) {
53 | 					$score += ($keyValue*(1/$cc * $this->rank[$v]));
54 | 				}
55 | 			}
56 | 			$tmp[$key] = $score;
57 | 		}
58 | 		$this->rank = $tmp;
59 | 	}
60 | 
61 | 
62 | 
63 | }
64 | 
65 | $map = [
66 | 		'a' => ['b', 'c', 'd'],// web 'a' (has out link): web 'b', web 'c', web 'd'
67 | 		'b' => ['a', 'd'],
68 | 		'c' => ['b'],
69 | 		'd' => ['b', 'c'],
70 | ];
71 | 
72 | 
73 | $example = new PageRank($map);
74 | $example->init();
75 | 
76 | echo '
';
77 | 
78 | for ($i = 0; $i < 10; $i++) {
79 | 	$example->caculate();
80 | 	var_dump($example->rank);
81 | }


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/README.md:
--------------------------------------------------------------------------------
 1 | - BPlusTree : B+树
 2 | 
 3 | - BTree : B树
 4 | 
 5 | - Hash : Hash表实现
 6 | 
 7 | - Heap : 堆实现
 8 |  - MaxHeap : 最大堆
 9 |  - MinHeap : 最小堆
10 | 
11 | - PageRank : 网页排名-简单PageRank实现
12 | 
13 | - RedBlackTree : 红黑树实现
14 |     - RedBlackTree : 红黑树实现
15 |     
16 | - SkipList : 跳跃表实现
17 |   - SkipList : 跳跃表实现
18 | 
19 | - Sort : 排序算法
20 |     - CompareSort : 比较类排序
21 |         - InsertSort : 插入类排序
22 |             - InsertSort : 插入排序
23 |         - MergeSort : 归并类排序
24 |             - MergeSort : 归并排序
25 |         - SelectSort : 选择类排序
26 |             - HeapSort : 堆排序
27 |         - SwapSort : 交换类排序
28 |             - BubbleSort : 冒泡排序
29 |             - QuickSort : 快速排序     
30 |     - NoCompareSort : 非比较类排序
31 |         - BucketSort : 桶排序
32 |         - CountSort : 计数排序
33 |         - RadixSort : 基数排序


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/RedBlackTree/README.md:
--------------------------------------------------------------------------------
1 | #### 红黑树


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/InsertSort/InsertSort.php:
--------------------------------------------------------------------------------
 1 | originalData = $original;
20 |         $this->resultData = $original;
21 |         $this->dataLen = count($original);
22 |     }
23 | 
24 |     public function sort()
25 |     {
26 |         for ($i = 0; $i < $this->dataLen; $i++) {
27 |             for ($j = $i; $j > 0; $j--) {
28 |                 if ($this->resultData[$j-1] > $this->resultData[$j]) {
29 |                     $tmp = $this->resultData[$j-1];
30 |                     $this->resultData[$j-1] = $this->resultData[$j];
31 |                     $this->resultData[$j] = $tmp;
32 |                 } else {
33 |                     break;
34 |                 }
35 |             }
36 |         }
37 |         return $this->resultData;
38 |     }
39 | }
40 | 
41 | $testData = [155, 19, 88, 12, 40, 29, 1, 23];
42 | 
43 | $insertSort = new InsertSort($testData);
44 | echo '
';
45 | var_dump($insertSort->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/InsertSort/ShellSort.php:
--------------------------------------------------------------------------------
 1 | 
 6 |  * @copyright liu hao
 7 |  *
 8 |  * 希尔排序
 9 |  *
10 |  * 1. 计算初始增量,一般开始的增量是序列长度/2
11 |  * 2. 按增量分组
12 |  * 3. 分组内排序
13 |  * 4. 增量减小,增量每次减小到之前增量的1/2,重复1.2步骤,直至增量为一
14 |  *
15 |  *
16 |  * 例如序列: 10, 3, 6, 9, 4
17 |  * 1. 序列长度是5,所以初始增量是5/2 = 2
18 |  * 2. 按增量为2分组
19 |  *  1 => 10, 6, 4
20 |  *  2 => 3, 9
21 |  * 3. 分组内排序
22 |  *  1 => 4, 6, 10
23 |  *  2 => 3, 9
24 |  *  序列变为: 4, 3, 6, 9, 10
25 |  *
26 |  * 4.增量减小到 2/2 = 1
27 |  *  按增量为1分组:
28 |  *  1 => 4, 3, 6, 9, 10
29 |  *  分组内排序:
30 |  *  1 => 3, 4, 6, 9, 10
31 |  *  因增量已为1,所以得到排序序列: 3, 4, 6, 9, 10
32 |  *
33 |  *
34 |  */
35 | 
36 | class ShellSort
37 | {
38 |     private $originalData = [];
39 |     private $resultData = [];
40 |     private $dataLen;
41 | 
42 |     public function __construct($original = [])
43 |     {
44 |         $this->originalData = $original;
45 |         $this->resultData = $original;
46 |         $this->dataLen = count($original);
47 |     }
48 | 
49 |     public function sort()
50 |     {
51 |         $step = $this->dataLen / 2;
52 |         while ($step >= 1) {
53 |             for ($i = 0; $i < $step; $i++) {
54 |                 for ($j = $i; $j < $this->dataLen; $j += $step) {
55 |                     for ($z = $j; $z >= $step; $z -= $step) {
56 |                         if ($this->resultData[$z] < $this->resultData[$z - $step]) {
57 |                             $tmp = $this->resultData[$z - $step];
58 |                             $this->resultData[$z - $step] = $this->resultData[$z];
59 |                             $this->resultData[$z] = $tmp;
60 |                         } else {
61 |                             break;
62 |                         }
63 |                     }
64 |                 }
65 |             }
66 |             $step /= 2;
67 |         }
68 | 
69 |         return $this->resultData;
70 |     }
71 | }
72 | 
73 | $testData = [111, 34, 10, 22, 99, 89, 123, 44, 79];
74 | 
75 | $shellSort = new ShellSort($testData);
76 | echo '
';
77 | var_dump($shellSort->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/MergeSort/MergeSort.php:
--------------------------------------------------------------------------------
 1 |  $arrayTwo[$j]) {
26 | 				$tmp[] = $arrayTwo[$j];
27 | 				$j = $j + 1;
28 | 			} else {
29 | 				$tmp[] = $arrayOne[$i];
30 | 				$i = $i + 1;
31 | 				$j = $j + 1;
32 | 			}
33 | 		}
34 | 
35 | 		while ($i < $oneLen) {
36 | 			$tmp[] = $arrayOne[$i];
37 | 			$i = $i + 1;
38 | 		}
39 | 
40 | 		while ($j < $twoLen) {
41 | 			$tmp[] = $arrayTwo[$j];
42 | 			$j = $j + 1;
43 | 		}
44 | 
45 | 		return $tmp;
46 | 	}
47 | 
48 | 	public function mergeSort($array)
49 | 	{
50 | 		$len = count($array);
51 | 
52 | 		if ($len <= 1) {
53 | 			return $array;
54 | 		}
55 | 
56 | 		$mid = (int)floor($len/2);
57 | 
58 | 		$leftArray = $this->mergeSort(array_slice($array, 0, $mid));
59 | 		$rightArray = $this->mergeSort(array_slice($array, $mid));
60 | 		
61 | 		return $this->mergeArray($leftArray, $rightArray);
62 | 	}
63 | }
64 | 
65 | 
66 | echo '
';
67 | 
68 | $example = [1, 3, 2, 9, 7, 11, 8, 10];
69 | 
70 | $test = new MergeSortTest();
71 | var_dump($test->mergeSort($example));
72 | 
73 | 


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/SelectSort/HeapSort.php:
--------------------------------------------------------------------------------
  1 | size++;
 17 | 			$this->insert($value);
 18 | 		}
 19 | 	}
 20 | 
 21 | 	abstract public function insert($value);
 22 | 
 23 | 	abstract public function delete();
 24 | 
 25 | 	public function sort()
 26 | 	{
 27 | 		$result = [];
 28 | 		$size = $this->size;
 29 | 		for ($i = 1; $i <= $size; $i++) {
 30 | 			$result[] = $this->delete();
 31 | 		}
 32 | 		return $result;
 33 | 	}
 34 | }
 35 | 
 36 | //最小堆
 37 | class MinHeap extends Heap
 38 | {
 39 | 	public function insert($value)
 40 | 	{
 41 | 		for ($i = $this->size; ($i > 0) && ($this->heap[floor($i/2)] > $value); $i = floor($i/2)) {
 42 | 			$this->heap[$i] = $this->heap[floor($i/2)];
 43 | 		}
 44 | 
 45 | 		$this->heap[$i] = $value;
 46 | 	}
 47 | 
 48 | 
 49 | 	public function delete()
 50 | 	{
 51 | 		$minValue = $this->heap[1];
 52 | 		$lastValue = $this->heap[$this->size--];
 53 | 		$child = 1;
 54 | 
 55 | 		for ($i = 1; $i*2 <= $this->size; $i = $child) {
 56 | 
 57 | 			$child = $i * 2;
 58 | 
 59 | 			$leftIndex = $child;
 60 | 			$rightIndex = $child + 1;
 61 | 
 62 | 			if (($child != $this->size) && ($this->heap[$leftIndex] > $this->heap[$rightIndex])) {
 63 | 				$child++;
 64 | 			}
 65 | 
 66 | 			if ($lastValue > $this->heap[$child]) {
 67 | 				$this->heap[$i] = $this->heap[$child];
 68 | 			} else {
 69 | 				break;
 70 | 			}
 71 | 		}
 72 | 
 73 | 		$this->heap[$i] = $lastValue;
 74 | 		return $minValue;
 75 | 	}
 76 | }
 77 | 
 78 | //最大堆
 79 | class MaxHeap extends Heap
 80 | {
 81 | 	public function insert($value)
 82 | 	{
 83 | 		for ($i = $this->size; (floor($i/2) > 0) && ($this->heap[floor($i/2)] < $value); $i = floor($i/2)) {
 84 | 			$this->heap[$i] = $this->heap[floor($i/2)];
 85 | 		}
 86 | 		$this->heap[$i] = $value;
 87 | 	}
 88 | 
 89 | 	public function delete()
 90 | 	{
 91 | 		$maxValue = $this->heap[1];
 92 | 		$lastValue = $this->heap[$this->size--];
 93 | 
 94 | 		$child = 1;
 95 | 
 96 | 		for ($i = 1; $i * 2 <= $this->size; $i = $child) {
 97 | 			$child = $i * 2;
 98 | 			$leftIndex = $child;
 99 | 			$rightIndex = $child + 1;
100 | 
101 | 
102 | 			if (($child != $this->size) && ($this->heap[$leftIndex] < $this->heap[$rightIndex])) {
103 | 				$child++;
104 | 			}
105 | 
106 | 			if ($this->heap[$child] > $lastValue) {
107 | 				$this->heap[$i] = $this->heap[$child];
108 | 			} else {
109 | 				break;
110 | 			}
111 | 		}
112 | 
113 | 		$this->heap[$i] = $lastValue;
114 | 		return $maxValue;
115 | 
116 | 	}
117 | }
118 | 
119 | 
120 | 
121 | $testData = [33, 4, 3, 2, 5, 6, 9, 10, 32, 23, 45, 11, 25];
122 | $minHeap = new MinHeap($testData);
123 | $maxHeap = new MaxHeap($testData);
124 | 
125 | echo '
';
126 | var_dump($minHeap->sort());
127 | var_dump($maxHeap->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/SelectSort/SimpleSelectSort.php:
--------------------------------------------------------------------------------
 1 | 
 6 |  * @copyright liu hao
 7 |  *
 8 |  * 简单选择排序
 9 |  * 1. 遍历剩余待排序序列,找出最值.
10 |  * 2. 将最值和待排序序列的第一个元素交换.
11 |  */
12 | 
13 | class SimpleSelectSort
14 | {
15 |     private $originalData = [];
16 |     private $resultData = [];
17 |     private $dataLen;
18 | 
19 |     public function __construct($original = [])
20 |     {
21 |         $this->originalData = $original;
22 |         $this->resultData = $original;
23 |         $this->dataLen = count($original);
24 |     }
25 | 
26 |     public function sort()
27 |     {
28 |         for ($i = 0; $i < $this->dataLen - 1; $i++) {
29 |             $tmp = $this->resultData[$i];
30 |             $tmpKey = $i;
31 |             for ($j = $i; $j < $this->dataLen; $j++) {
32 |                 if ($tmp > $this->resultData[$j]) {
33 |                     $tmp = $this->resultData[$j];
34 |                     $tmpKey = $j;
35 |                 }
36 |             }
37 | 
38 |             if ($tmpKey != $i) {
39 |                 $this->resultData[$tmpKey] = $this->resultData[$i];
40 |                 $this->resultData[$i] = $tmp;
41 |             }
42 |         }
43 |         return $this->resultData;
44 |     }
45 | }
46 | 
47 | $testData = [12, 55, 99, 22, 33, 25, 11, 44, 78];
48 | 
49 | $simpleSelectSort = new SimpleSelectSort($testData);
50 | echo '
';
51 | var_dump($simpleSelectSort->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/SwapSort/BubbleSort.php:
--------------------------------------------------------------------------------
 1 | 
 6 |  * @copyright liu hao
 7 |  *
 8 |  * 冒泡排序
 9 |  *
10 |  * 1. 输入序列长度为n
11 |  * 2. 进行n - 1次处理,第一次将最大值移动到序列末尾,第二次将次大值移动到序列倒数第2位置,依次类推
12 |  * 3. 最终得到一个升序排列的序列
13 |  *
14 |  *
15 |  */
16 | 
17 | class BubbleSort
18 | {
19 |     private $originalData = [];
20 |     private $resultData = [];
21 |     private $dataLen;
22 | 
23 |     public function __construct($original = [])
24 |     {
25 |         $this->originalData = $original;
26 |         $this->resultData = $original;
27 |         $this->dataLen = count($original);
28 |     }
29 | 
30 |     public function sort()
31 |     {
32 |         for ($i = 0; $i < $this->dataLen - 1; $i++) {
33 |             for ($j = 0; $j < $this->dataLen - $i -1; $j++) {
34 |                 if ($this->resultData[$j+1] < $this->resultData[$j]) {
35 |                     $tmp = $this->resultData[$j+1];
36 |                     $this->resultData[$j+1] = $this->resultData[$j];
37 |                     $this->resultData[$j] = $tmp;
38 |                 }
39 |             }
40 |         }
41 |         return $this->resultData;
42 |     }
43 | }
44 | 
45 | $testData = [23, 45, 8, 11, 10, 31, 55, 96, 30, 22];
46 | 
47 | $bubbleSort = new BubbleSort($testData);
48 | echo '
';
49 | var_dump($bubbleSort->sort());


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/CompareSort/SwapSort/QuickSort.php:
--------------------------------------------------------------------------------
 1 | originalData = $original;
24 |     }
25 | 
26 |     public function sort()
27 | 	{
28 | 	    $this->resultData = $this->quick($this->originalData);
29 | 	    return $this->resultData;
30 | 	}
31 | 
32 | 	protected function quick($originalData)
33 |     {
34 |         $lenght = count($originalData);
35 | 
36 |         if ($lenght <= 1) {
37 |             return $originalData;
38 |         }
39 | 
40 | 
41 |         $pivot = $this->threeMiddleValue($originalData, 0, $lenght - 1);
42 | 
43 |         $leftData = [];
44 |         $rightData = [];
45 | 
46 |         for($i = 0; $i < $lenght; $i++) {
47 |             if ($originalData[$i] < $pivot) {
48 |                 $leftData[] = $originalData[$i];
49 |             } else if ($originalData[$i] > $pivot){
50 |                 $rightData[] = $originalData[$i];
51 |             }
52 |         }
53 | 
54 |         $leftData = $this->quick($leftData);
55 |         $rightData = $this->quick($rightData);
56 | 
57 |         return array_merge($leftData, [$pivot], $rightData);
58 |     }
59 | 
60 | 	public function threeMiddleValue($arr, $left, $right)
61 | 	{
62 | 		$result = null;
63 | 
64 | 		$middle = floor(($left + $right)/2);
65 | 
66 | 		if ($arr[$left] > $arr[$right]) {
67 | 			if ($arr[$left] < $arr[$middle]) {
68 | 				$result = $arr[$left];
69 | 			} else if ($arr[$right] > $arr[$middle]) {
70 | 				$result = $arr[$right];
71 | 			} else {
72 | 				$result = $arr[$middle];
73 | 			}
74 | 		} else {
75 | 			if ($arr[$right] < $arr[$middle]) {
76 | 				$result = $arr[$right];
77 | 			} else if ($arr[$left] > $arr[$middle]) {
78 | 				$result = $arr[$left];
79 | 			} else {
80 | 				$result = $arr[$middle];
81 | 			}
82 | 		}
83 | 
84 | 		return $result;
85 | 	}
86 | }
87 | 
88 | $testData = [7, 3, 10, 5, 1, 8];
89 | $quickSort = new QuickSort($testData);
90 | echo '
';
91 | var_dump($quickSort->sort());
92 | 


--------------------------------------------------------------------------------
/Php/DataStructureAndAlgorithm/Sort/NoCompareSort/CountSort.php:
--------------------------------------------------------------------------------
  1 | 
  6 |  * @copyright liu hao
  7 |  *
  8 |  * 计数排序
  9 |  *
 10 |  *
 11 |  * 1. 获取序列中的最小值min和最大值max O(n)
 12 |  * 2. 统计min - max之间所有值在序列中的出现次数 O(n)
 13 |  * 3. 顺序输出min - max的所有值,次数为0不输出,其余次数为多少就输出多少 O(k) k为数据范围
 14 |  *
 15 |  * 例如序列为: 2, 4, 6, 9, 4, 8
 16 |  *
 17 |  * 1. min = 2, max = 9, n为6,k为8
 18 |  * 2. 统计出现次数为
 19 |  *      [2 => 1, 3 => 0, 4 => 2, 5 => 0, 6 => 1, 7 => 0, 8 => 1, 9 => 1]
 20 |  * 3. 输出结果为
 21 |  *     2, 4, 4, 6, 8, 9
 22 |  *
 23 |  * 很明显,计数排序的复杂度为O(n) + O(k),也就是和数据量和数据范围有关.
 24 |  * 若n和k相近,则可认为是O(n)
 25 |  * 同时,因为要统计出现次数,如果数据范围过大而数据又很稀疏,造成的空间浪费比较大
 26 |  */
 27 | 
 28 | class CountSort
 29 | {
 30 |     private $originalData = [];
 31 |     private $rangeMap = [];
 32 |     private $resultData = [];
 33 | 
 34 |     public function __construct($original = [])
 35 |     {
 36 |         $this->originalData = $original;
 37 |     }
 38 | 
 39 |     public function sort()
 40 |     {
 41 |         list($min, $max) = $this->calculateDataRange();
 42 |         $this->statisticNumberOfOccurrence($min, $max);
 43 |         $this->resultData = $this->generateResult();
 44 |         return $this->resultData;
 45 |     }
 46 | 
 47 |     protected function calculateDataRange()
 48 |     {
 49 |         $max = null;
 50 |         $min = null;
 51 | 
 52 |         foreach ($this->originalData as $value) {
 53 |             if (!is_null($max)) {
 54 |                 if ($value > $max) {
 55 |                     $max = $value;
 56 |                 }
 57 |             } else {
 58 |                 $max = $value;
 59 |             }
 60 | 
 61 |             if (!is_null($min)) {
 62 |                 if ($value < $min) {
 63 |                     $min = $value;
 64 |                 }
 65 |             } else {
 66 |                 $min = $value;
 67 |             }
 68 |         }
 69 | 
 70 |         return [$min, $max];
 71 |     }
 72 | 
 73 |     protected function statisticNumberOfOccurrence($min, $max)
 74 |     {
 75 |         for ($i = $min; $i <= $max; $i++) {
 76 |             $this->rangeMap[$i] = 0;
 77 |         }
 78 | 
 79 |         foreach ($this->originalData as $value) {
 80 |             $this->rangeMap[$value]++;
 81 |         }
 82 |     }
 83 | 
 84 |     protected function generateResult()
 85 |     {
 86 |         $result = [];
 87 | 
 88 |         foreach ($this->rangeMap as $key => $value) {
 89 |             if ($value != 0) {
 90 |                 for ($i = 0; $i < $value; $i++) {
 91 |                     array_push($result, $key);
 92 |                 }
 93 |             }
 94 |         }
 95 |         return $result;
 96 |     }
 97 | }
 98 | 
 99 | $testData = [2, 3, 4, 3, 10, 30, 20, 15, 10, 12, 33];
100 | 
101 | $countSort = new CountSort($testData);
102 | echo '
';
103 | var_dump($countSort->sort());


--------------------------------------------------------------------------------
/Php/DesignPatterns/Adapter/Adapter.php:
--------------------------------------------------------------------------------
 1 | \n";
30 | 	}
31 | 
32 | 	public function roar()
33 | 	{
34 | 		echo "ohoooooo..
\n"; 35 | } 36 | } 37 | 38 | 39 | class LittleBoy implements PersonInterface 40 | { 41 | public function walk() 42 | { 43 | echo "I am walking
\n"; 44 | } 45 | 46 | public function speak() 47 | { 48 | echo "I am speaking
\n"; 49 | } 50 | } 51 | 52 | 53 | class MonkeyAdapter implements PersonInterface 54 | { 55 | private $monkey; 56 | 57 | public function __construct(MonkeyInterface $monkey) 58 | { 59 | $this->monkey = $monkey; 60 | } 61 | 62 | public function walk() 63 | { 64 | $this->monkey->jump(); 65 | } 66 | 67 | public function speak() 68 | { 69 | $this->monkey->roar(); 70 | } 71 | } 72 | 73 | 74 | class Test 75 | { 76 | public function run() 77 | { 78 | $person = new LittleBoy(); 79 | $person->walk(); 80 | $person->speak(); 81 | 82 | $monkey = new LittleMonkey(); 83 | $monkeyAdapter = new MonkeyAdapter($monkey); 84 | 85 | $monkeyAdapter->walk(); 86 | $monkeyAdapter->speak(); 87 | } 88 | } 89 | 90 | 91 | $test = new Test(); 92 | 93 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Composite/Composite.php: -------------------------------------------------------------------------------- 1 | human = $human; 38 | } 39 | } 40 | 41 | class WatchDecorator extends HumanDecorator 42 | { 43 | public function display() 44 | { 45 | echo $this->human->display()." with a Watch"; 46 | } 47 | } 48 | 49 | class GlassesDecorator extends HumanDecorator 50 | { 51 | public function display() 52 | { 53 | echo $this->human->display()." with a Glasses"; 54 | } 55 | } 56 | 57 | 58 | class Test 59 | { 60 | public function run() 61 | { 62 | $yellowHuman = new YellowHuman(); 63 | $blackHuman = new BlackHuman(); 64 | 65 | 66 | $yellowHumanWithWatch = new WatchDecorator($yellowHuman); 67 | $blackHumanWithGlasses = new GlassesDecorator($blackHuman); 68 | 69 | $yellowHumanWithWatchWithGlasses = new GlassesDecorator($yellowHumanWithWatch); 70 | 71 | $yellowHuman->display(); 72 | echo "
\n"; 73 | $blackHuman->display(); 74 | echo "
\n"; 75 | 76 | $yellowHumanWithWatch->display(); 77 | echo "
\n"; 78 | $blackHumanWithGlasses->display(); 79 | echo "
\n"; 80 | 81 | $yellowHumanWithWatchWithGlasses->display(); 82 | } 83 | } 84 | 85 | $test = new Test(); 86 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Facade/Facade.php: -------------------------------------------------------------------------------- 1 | \n"; 38 | } 39 | 40 | public function close() 41 | { 42 | echo "close the door
\n"; 43 | } 44 | } 45 | 46 | class Light implements LightInterface 47 | { 48 | public function on() 49 | { 50 | echo "turn on the light
\n"; 51 | } 52 | 53 | public function off() 54 | { 55 | echo "turn off the light
\n"; 56 | } 57 | } 58 | 59 | class Air implements AirInterface 60 | { 61 | public function start() 62 | { 63 | echo "start the air
\n"; 64 | } 65 | 66 | public function stop() 67 | { 68 | echo "stop the air
\n"; 69 | } 70 | } 71 | 72 | 73 | 74 | class House 75 | { 76 | private $door; 77 | private $light; 78 | private $air; 79 | 80 | public function __construct(DoorInterface $door, LightInterface $light, AirInterface $air) 81 | { 82 | $this->door = $door; 83 | $this->light = $light; 84 | $this->air = $air; 85 | } 86 | 87 | public function goBackHome() 88 | { 89 | $this->door->open(); 90 | $this->light->on(); 91 | $this->air->start(); 92 | } 93 | 94 | public function leaveHome() 95 | { 96 | $this->door->close(); 97 | $this->light->off(); 98 | $this->air->stop(); 99 | } 100 | } 101 | 102 | 103 | class Test 104 | { 105 | public function run() 106 | { 107 | $door = new Door(); 108 | $light = new Light(); 109 | $air = new Air(); 110 | 111 | 112 | $house = new House($door, $light, $air); 113 | 114 | $house->goBackHome(); 115 | echo "
"; 116 | $house->leaveHome(); 117 | } 118 | } 119 | 120 | $test = new Test(); 121 | 122 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Factory/FactoryMethod.php: -------------------------------------------------------------------------------- 1 | bake()等方法,而这些方法是由Cake抽象定义的,所以CakeStore依赖于Cake.而具体的Cake对象也依赖于抽象Cake.这种方式避免了我们的CakeStore依赖于具体的Cake类,所以这是依赖倒置原则的很好示例。 9 | * 10 | */ 11 | 12 | //抽象蛋糕店 13 | abstract class CakeStore 14 | { 15 | public function orderCake() 16 | { 17 | $cake = $this->createCake(); 18 | 19 | $cake->bake(); 20 | $cake->package(); 21 | } 22 | 23 | abstract function createCake(); 24 | } 25 | 26 | //抽象蛋糕 27 | abstract class Cake 28 | { 29 | abstract public function bake(); 30 | 31 | abstract public function package(); 32 | } 33 | 34 | //具体蛋糕类 35 | class BeiJingCake extends Cake 36 | { 37 | public function bake() 38 | { 39 | echo "BeiJing cake is baking
\n"; 40 | } 41 | 42 | public function package() 43 | { 44 | echo "BeiJing cake is packaging
\n"; 45 | } 46 | } 47 | 48 | class ShangHaiCake extends Cake 49 | { 50 | public function bake() 51 | { 52 | echo "Shang Hai cake is baking
\n"; 53 | } 54 | 55 | public function package() 56 | { 57 | echo "Shang Hai cake is packaging
\n"; 58 | } 59 | } 60 | 61 | //具体蛋糕店类 62 | class BeiJingCakeStore extends CakeStore 63 | { 64 | public function createCake() 65 | { 66 | return new BeiJingCake(); 67 | } 68 | } 69 | 70 | 71 | class ShangHaiCakeStore extends CakeStore 72 | { 73 | public function createCake() 74 | { 75 | return new ShangHaiCake(); 76 | } 77 | } 78 | 79 | 80 | class Test 81 | { 82 | public function run() 83 | { 84 | $beijingStore = new BeiJingCakeStore(); 85 | $shanghaiStore = new ShangHaiCakeStore(); 86 | 87 | $beijingStore->orderCake(); 88 | $shanghaiStore->orderCake(); 89 | } 90 | } 91 | 92 | $test = new Test(); 93 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Factory/SimpleFactory.php: -------------------------------------------------------------------------------- 1 | \n"; 25 | } 26 | 27 | public function close() 28 | { 29 | echo "White Door Close!
\n"; 30 | } 31 | } 32 | class BlackDoor extends Door 33 | { 34 | public function open() 35 | { 36 | echo "Black Door Open!
\n"; 37 | } 38 | 39 | public function close() 40 | { 41 | echo "Black Door Close!
\n"; 42 | } 43 | } 44 | 45 | class NilDoor extends Door 46 | { 47 | public function open() 48 | {} 49 | 50 | public function close() 51 | {} 52 | } 53 | 54 | 55 | class SimpleFactory 56 | { 57 | public function create($config = []) 58 | { 59 | $object = null; 60 | 61 | if (is_array($config) && !empty($config)) { 62 | $className = array_shift($config).'Door'; 63 | $object = new $className($config); 64 | } else { 65 | $object = new NilDoor(); 66 | } 67 | return $object; 68 | } 69 | } 70 | 71 | class Test 72 | { 73 | public function run() 74 | { 75 | $factory = new SimpleFactory(); 76 | 77 | $doorOne = $factory->create(['Black']); 78 | $doorTwo = $factory->create(['White']); 79 | 80 | $doorOne->open(); 81 | $doorOne->close(); 82 | 83 | $doorTwo->open(); 84 | $doorTwo->close(); 85 | } 86 | } 87 | 88 | $test = new Test(); 89 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Iterator/Iterator.php: -------------------------------------------------------------------------------- 1 | data = $data; 33 | } 34 | 35 | public function createIterator() 36 | { 37 | return new FirstIterator($this->data); 38 | } 39 | } 40 | 41 | 42 | class FirstIterator implements MyIterator 43 | { 44 | private $aggregate; 45 | private $position; 46 | 47 | public function __construct(array $aggregate = []) 48 | { 49 | $this->aggregate = $aggregate; 50 | $this->position = 0; 51 | } 52 | 53 | public function hasNext() 54 | { 55 | return isset($this->aggregate[$this->position]); 56 | } 57 | 58 | public function next() 59 | { 60 | return $this->aggregate[$this->position++]; 61 | } 62 | 63 | public function remove() 64 | { 65 | return; 66 | } 67 | } 68 | 69 | 70 | class Test 71 | { 72 | public function run() 73 | { 74 | $data = [4, 2, 5, 1, 3]; 75 | 76 | $aggregate = new FirstAggregate($data); 77 | $iterator = $aggregate->createIterator(); 78 | 79 | while ($iterator->hasNext()) { 80 | var_dump($iterator->next()); 81 | } 82 | } 83 | } 84 | 85 | $test = new Test(); 86 | $test->run(); 87 | -------------------------------------------------------------------------------- /Php/DesignPatterns/Pipeline/Pipeline.php: -------------------------------------------------------------------------------- 1 | payLoad = $payLoad; 62 | } 63 | 64 | public function pipe(StageInterface $stage) 65 | { 66 | $this->pipes[] = $stage; 67 | return $this; 68 | } 69 | 70 | public function process() 71 | { 72 | foreach ($this->pipes as $eachPipe) 73 | { 74 | $this->payLoad = call_user_func([$eachPipe, 'handle'], $this->payLoad); 75 | } 76 | 77 | return $this->payLoad; 78 | } 79 | } 80 | 81 | 82 | class Test 83 | { 84 | public function run() 85 | { 86 | $payLoad = 10; 87 | 88 | $stageAddOne = new StageAddOne(); 89 | $stageMultiTwo = new StageMultiTwo(); 90 | $stageAddTwo = new StageAddTwo(); 91 | 92 | $pipe = new Pipeline($payLoad); 93 | 94 | return $pipe->pipe($stageAddOne)->pipe($stageMultiTwo)->pipe($stageAddTwo)->process(); 95 | } 96 | } 97 | 98 | $test = new Test(); 99 | 100 | echo '
';
101 | var_dump($test->run());


--------------------------------------------------------------------------------
/Php/DesignPatterns/Proxy/Proxy.php:
--------------------------------------------------------------------------------
 1 | run();


--------------------------------------------------------------------------------
/Php/DesignPatterns/README.md:
--------------------------------------------------------------------------------
 1 | - Adapter : 适配器模式
 2 | - Command : 命令模式
 3 | - Composite : 组合模式
 4 | - Decorator : 装饰者模式
 5 | - Facade : 门面模式
 6 | - Factory : 工厂模式
 7 | - Iterator : 迭代器模式
 8 | - Observer : 观察者模式
 9 | - Pipeline : 管道模式
10 | - Proxy : 代理模式
11 | - SingleTon : 单例模式
12 | - State : 状态模式
13 | - Strategy : 策略模式
14 | - TemplateMethod : 模板方法模式


--------------------------------------------------------------------------------
/Php/DesignPatterns/Singleton/Singleton.php:
--------------------------------------------------------------------------------
 1 | pro = 'Hello';
39 | 
40 | 		var_dump($singletonOne->pro);
41 | 
42 | 		$singletonTwo = Singleton::getInstance();
43 | 
44 | 		var_dump($singletonTwo->pro);
45 | 	}
46 | }
47 | 
48 | $test = new Test();
49 | $test->run();


--------------------------------------------------------------------------------
/Php/DesignPatterns/Singleton/StrictSingleton.php:
--------------------------------------------------------------------------------
 1 | pro = 'Hello';
40 | 
41 | 		$singletonTwo = Singleton::getInstance();
42 | 		$singletonTwo->pro = 'World';
43 | 
44 | 		// $singletonThree = clone $singletonOne;
45 | 		// $singletonThree->pro = 'Test';
46 | 
47 | 		var_dump($singletonOne->pro);
48 | 		var_dump($singletonTwo->pro);
49 | 		// var_dump($singletonThree->pro);
50 | 	}
51 | }
52 | 
53 | $test = new Test();
54 | $test->run();


--------------------------------------------------------------------------------
/Php/DesignPatterns/Strategy/hasSetter.php:
--------------------------------------------------------------------------------
 1 | weapon->fight();
28 | 	}
29 | 
30 | 	public function setWeapon($weapon)
31 | 	{
32 | 		$this->weapon = $weapon;
33 | 	}
34 | }
35 | 
36 | interface Weapon
37 | {
38 | 	public function fight();
39 | }
40 | 
41 | class Tom extends Character
42 | {
43 | 	public function __construct(Weapon $weapon)
44 | 	{
45 | 		$this->weapon = $weapon;
46 | 	}
47 | }
48 | 
49 | 
50 | 
51 | class Knife implements Weapon
52 | {
53 | 	public function fight()
54 | 	{
55 | 		echo "This is Knife!
\n"; 56 | } 57 | } 58 | 59 | class Fork implements Weapon 60 | { 61 | public function fight() 62 | { 63 | echo "This is Fork!
\n"; 64 | } 65 | } 66 | 67 | class NilWeapon implements Weapon 68 | { 69 | public function fight() 70 | { 71 | echo "No Weapon!
\n"; 72 | } 73 | } 74 | 75 | 76 | class Test 77 | { 78 | public function run() 79 | { 80 | $noWeapon = new NilWeapon(); 81 | $knife = new Knife(); 82 | $fork = new Fork(); 83 | 84 | $tom = new Tom($noWeapon); 85 | $tom->fight(); 86 | 87 | $tom->setWeapon($knife); 88 | $tom->fight(); 89 | 90 | $tom->setWeapon($fork); 91 | $tom->fight(); 92 | } 93 | } 94 | 95 | $test = new Test(); 96 | 97 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/Strategy/noSetter.php: -------------------------------------------------------------------------------- 1 | weapon->fight(); 30 | } 31 | } 32 | 33 | interface Weapon 34 | { 35 | public function fight(); 36 | } 37 | 38 | class Tom extends Character 39 | { 40 | public function __construct(Weapon $weapon) 41 | { 42 | $this->weapon = $weapon; 43 | } 44 | } 45 | 46 | 47 | 48 | class Knife implements Weapon 49 | { 50 | public function fight() 51 | { 52 | echo "This is Knife!
\n"; 53 | } 54 | } 55 | 56 | class Fork implements Weapon 57 | { 58 | public function fight() 59 | { 60 | echo "This is Fork!
\n"; 61 | } 62 | } 63 | 64 | class NilWeapon implements Weapon 65 | { 66 | public function fight() 67 | { 68 | echo "No Weapon!
\n"; 69 | } 70 | } 71 | 72 | 73 | class Test 74 | { 75 | public function run() 76 | { 77 | $noWeapon = new NilWeapon(); 78 | $knife = new Knife(); 79 | $fork = new Fork(); 80 | 81 | $tomA = new Tom($noWeapon); 82 | $tomA->fight(); 83 | 84 | $tomB = new Tom($knife); 85 | $tomB->fight(); 86 | 87 | $tomC = new Tom($fork); 88 | $tomC->fight(); 89 | } 90 | } 91 | 92 | $test = new Test(); 93 | 94 | $test->run(); -------------------------------------------------------------------------------- /Php/DesignPatterns/TemplateMethod/TemplateMethod.php: -------------------------------------------------------------------------------- 1 | connectElectricity(); 26 | $this->openPower(); 27 | $this->display(); 28 | } 29 | 30 | public function connectElectricity() 31 | { 32 | echo "The Electricity is coming!
\n"; 33 | } 34 | 35 | abstract public function openPower(); 36 | 37 | abstract public function display(); 38 | } 39 | 40 | class RunComputer extends RunMachineTemplateMethod 41 | { 42 | public function openPower() 43 | { 44 | echo "Computer open power!
\n"; 45 | } 46 | 47 | public function display() 48 | { 49 | echo "Computer display!
\n"; 50 | } 51 | } 52 | 53 | class RunTv extends RunMachineTemplateMethod 54 | { 55 | public function openPower() 56 | { 57 | echo "TV open power!
\n"; 58 | } 59 | 60 | public function display() 61 | { 62 | echo "TV display!
\n"; 63 | } 64 | } 65 | 66 | 67 | class Test 68 | { 69 | public function run() 70 | { 71 | $computer = new RunComputer(); 72 | $tv = new RunTv(); 73 | 74 | $computer->run(); 75 | echo "
\n"; 76 | $tv->run(); 77 | } 78 | } 79 | 80 | $test = new Test(); 81 | $test->run(); -------------------------------------------------------------------------------- /Php/FakeApi/.gitignore: -------------------------------------------------------------------------------- 1 | log -------------------------------------------------------------------------------- /Php/FakeApi/Log.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\FakeApi; 10 | 11 | 12 | class Log 13 | { 14 | public static $logFile = __DIR__.'/log'; 15 | 16 | public static function write($msg) 17 | { 18 | $logP = fopen(self::$logFile, 'a+'); 19 | fwrite($logP, $msg."\n"); 20 | fclose($logP); 21 | } 22 | } -------------------------------------------------------------------------------- /Php/FakeApi/MyParts/index.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once dirname(dirname(__DIR__)) . '/vendor/autoload.php'; 10 | 11 | $params = file_get_contents('php://input'); 12 | 13 | try { 14 | $myParts = new PHPCodes\FakeApi\MyParts\MyParts(json_decode($params, true)); 15 | $myParts->exec(); 16 | } catch (\Exception $e) { 17 | \PHPCodes\FakeApi\Log::write($e->getMessage()); 18 | } 19 | -------------------------------------------------------------------------------- /Php/FileOperation/DirTranverse/DirTranverse.php: -------------------------------------------------------------------------------- 1 | '; 25 | if ($file == '.' || $file == '..') { 26 | continue; 27 | } 28 | 29 | if (is_dir($currentDir.'/'.$file)) { 30 | $sum++; 31 | // echo $sum; 32 | $queue[] = $currentDir.'/'.$file; 33 | } 34 | } 35 | closedir($handle); 36 | } 37 | } 38 | 39 | return $sum; 40 | } 41 | 42 | var_dump(sumDir($dir)); -------------------------------------------------------------------------------- /Php/FileOperation/ExcelColIncrease/ExcelColIncrease.php: -------------------------------------------------------------------------------- 1 | = 0) && ($step <= 26)) { 13 | switch (strlen($start)) { 14 | case 1: 15 | if (($start >= 'A') && ($start <= 'Z')) { 16 | $res = ord($start) + $step; 17 | if ($res <= ord('Z')) { 18 | $res = chr($res); 19 | } else { 20 | $res = 'A'.chr($res - 26); 21 | } 22 | } 23 | break; 24 | case 2: 25 | if (($start[1] >= 'A') && ($start[1] <= 'Z')) { 26 | $prefix = $start[0]; 27 | $suffix = $start[1]; 28 | 29 | $res = ord($suffix) + $step; 30 | if ($res <= ord('Z')) { 31 | $res = $prefix.chr($res); 32 | } else { 33 | $res = chr(ord($prefix) + 1).chr($res - 26); 34 | } 35 | } 36 | break; 37 | default: 38 | break; 39 | } 40 | } 41 | return $res; 42 | } 43 | 44 | public function test() 45 | { 46 | $start = 'A'; 47 | for ($i = 0; $i < 100; $i++) { 48 | var_dump($start); 49 | $start = $this->colIncrease($start); 50 | } 51 | } 52 | } 53 | 54 | $example = new ExcelColIncrease(); 55 | $example->test(); -------------------------------------------------------------------------------- /Php/FileOperation/GenerateBigFile/GenerageBigFile.php: -------------------------------------------------------------------------------- 1 | fwrite($str); 28 | } 29 | $example->fflush(); 30 | 31 | } 32 | 33 | echo date("Y-m-d H:i:s", time())."\n"; -------------------------------------------------------------------------------- /Php/FileOperation/README.md: -------------------------------------------------------------------------------- 1 | #### 目录和文件操作 2 | - DirTranverse : 非递归方式实现目录数量统计 3 | - ExcelColIncrease : excel列标识自增方法 4 | - GenerateBigFile : 大文件生成 -------------------------------------------------------------------------------- /Php/FilterSensitiveWord/README.md: -------------------------------------------------------------------------------- 1 | #### 敏感词过滤 2 | - FilterSensitiveWord : 简单的基于DFA算法的敏感词过滤第一版 [博客地址](https://blog.csdn.net/aikiller/article/details/78797864) 3 | - FilterSensitiveWord_2 : 简单的基于DFA算法的敏感词过滤第二版 [博客地址](https://blog.csdn.net/AIkiller/article/details/80287594) -------------------------------------------------------------------------------- /Php/HyperLogLog/Bucket.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | class Bucket 10 | { 11 | private $maxTailZeroCount = 0; 12 | 13 | private function calculateTailZeroCount($number) 14 | { 15 | $tailZeroCount = 0; 16 | 17 | for ($i = 0; $i < 32; $i++) { 18 | if (($number >> $i << $i) !== $number) { 19 | $tailZeroCount = $i - 1; 20 | break; 21 | } 22 | } 23 | 24 | return $tailZeroCount; 25 | } 26 | 27 | public function random() 28 | { 29 | $max = pow(2, 32) - 1; 30 | 31 | $value = mt_rand(0, $max); 32 | 33 | $tailZeroCount = $this->calculateTailZeroCount($value); 34 | 35 | if ($tailZeroCount > $this->maxTailZeroCount) { 36 | $this->maxTailZeroCount = $tailZeroCount; 37 | } 38 | } 39 | 40 | public function getMaxTailZeroCount() 41 | { 42 | return $this->maxTailZeroCount; 43 | } 44 | } -------------------------------------------------------------------------------- /Php/HyperLogLog/HyperLogLog.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | require_once './Bucket.php'; 9 | 10 | class HyperLogLog 11 | { 12 | 13 | private $bucketMap = []; 14 | private $bucketCount = 16384; 15 | 16 | public function __construct($bucketCount = 16384) 17 | { 18 | $this->bucketCount = $bucketCount; 19 | 20 | for ($i = 0; $i < $bucketCount; $i++) { 21 | $this->bucketMap[$i] = new Bucket(); 22 | } 23 | } 24 | 25 | public function add($value) 26 | { 27 | $number = crc32($value); 28 | 29 | $bucketOffset = (($number & 0xffff0000) >> 16) % $this->bucketCount; 30 | 31 | $this->getBucket($bucketOffset)->random(); 32 | } 33 | 34 | public function count() 35 | { 36 | $number = 0.0; 37 | $notEmptyCount = 0; 38 | 39 | for ($i = 0; $i < $this->bucketCount; $i++) { 40 | $division = floatval($this->getBucket($i)->getMaxTailZeroCount()); 41 | if ($division != 0) { 42 | $number += 1.0 / $division; 43 | $notEmptyCount++; 44 | } 45 | } 46 | 47 | $avg = floatval($notEmptyCount) / $number; 48 | return round(pow(2, $avg) * $notEmptyCount); 49 | } 50 | 51 | /** 52 | * @param $offset 53 | * @return Bucket 54 | */ 55 | private function getBucket($offset) 56 | { 57 | return $this->bucketMap[$offset]; 58 | } 59 | } 60 | 61 | -------------------------------------------------------------------------------- /Php/HyperLogLog/README.md: -------------------------------------------------------------------------------- 1 | #### 模拟redis的HyperLogLog数据结构 2 | 3 | 执行Test.php文件 -------------------------------------------------------------------------------- /Php/HyperLogLog/Test.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | require_once './HyperLogLog.php'; 9 | 10 | class Test 11 | { 12 | public function run() 13 | { 14 | $hyper = new HyperLogLog(); 15 | 16 | for ($i = 0; $i < 10000000; $i++) { 17 | $hyper->add('Test01'.$i); 18 | } 19 | 20 | echo $hyper->count(); 21 | } 22 | } 23 | 24 | $test = new Test(); 25 | $test->run(); -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/ImplementQueueWithTwoStack/Queue.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\InterestingQuestion\Stack\ImplementQueueWithTwoStack; 10 | 11 | 12 | class Queue 13 | { 14 | /** 15 | * @var \SplStack 16 | */ 17 | protected $stackPush; 18 | 19 | /** 20 | * @var \SplStack 21 | */ 22 | protected $stackPop; 23 | 24 | public function __construct() 25 | { 26 | $this->stackPush = new \SplStack(); 27 | $this->stackPop = new \SplStack(); 28 | } 29 | 30 | public function add($value) 31 | { 32 | $this->stackPush->push($value); 33 | } 34 | 35 | public function poll() 36 | { 37 | if ($this->isEmpty()) { 38 | throw new \Exception('Queue is empty!'); 39 | } else if ($this->stackPop->isEmpty()) { 40 | while (!$this->stackPush->isEmpty()) { 41 | $this->stackPop->push($this->stackPush->pop()); 42 | } 43 | } 44 | 45 | return $this->stackPop->pop(); 46 | } 47 | 48 | public function peek() 49 | { 50 | if ($this->isEmpty()) { 51 | throw new \Exception('Queue is empty!'); 52 | } else if ($this->stackPop->isEmpty()) { 53 | while (!$this->stackPush->isEmpty()) { 54 | $this->stackPop->push($this->stackPush->pop()); 55 | } 56 | } 57 | 58 | return $this->stackPop->top(); 59 | } 60 | 61 | public function isEmpty() 62 | { 63 | return $this->stackPush->isEmpty() && $this->stackPop->isEmpty(); 64 | } 65 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/ImplementQueueWithTwoStack/QueueExample.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once "Queue.php"; 10 | 11 | $queue = new \PHPCodes\InterestingQuestion\Stack\ImplementQueueWithTwoStack\Queue(); 12 | 13 | $testData = [12, 1, "a", "b", "dd"]; 14 | 15 | foreach ($testData as $value) { 16 | $queue->add($value); 17 | } 18 | 19 | while (!$queue->isEmpty()) { 20 | var_dump($queue->peek()); 21 | var_dump($queue->poll()); 22 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/ImplementQueueWithTwoStack/README.md: -------------------------------------------------------------------------------- 1 | #### 题目 2 | 编写一个类,用两个栈实现队列,支持队列的基本操作(add,poll,peek) 3 | add : 在队头部添加一个元素 4 | poll: 在队尾弹出一个元素 5 | peek: 在队头弹出一个元素 6 | 7 | #### 方案 8 | 9 | -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackReverse/README.md: -------------------------------------------------------------------------------- 1 | ### 如何仅用递归函数和栈操作逆序一个栈 2 | 3 | #### 题目 4 | 一个栈依次压入1,2,3,4,5,那么从栈顶到栈底分别为5,4,3,2,1。 5 | 将这个栈转置后,从栈顶到栈底为1,2,3,4,5,也就是实现栈中元素的逆序, 6 | 但是只能用递归函数来实现,不能用其它数据结构。 -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackReverse/ReverseStack.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\InterestingQuestion\Stack\StackReverse; 10 | 11 | 12 | class ReverseStack 13 | { 14 | /** 15 | * @var \SplStack 16 | */ 17 | protected $stack; 18 | 19 | public function __construct(array $list = []) 20 | { 21 | $stack = new \SplStack(); 22 | foreach ($list as $value) { 23 | $stack->push($value); 24 | } 25 | $this->stack = $stack; 26 | 27 | //逆序 28 | $this->reverse(); 29 | } 30 | 31 | protected function reverse() 32 | { 33 | if ($this->stack->isEmpty()) { 34 | return; 35 | } 36 | 37 | $value = $this->popValue(); 38 | $this->reverse(); 39 | $this->stack->push($value); 40 | } 41 | 42 | protected function popValue() 43 | { 44 | $value = $this->stack->pop(); 45 | 46 | if ($this->stack->isEmpty()) { 47 | return $value; 48 | } else { 49 | $last = $this->popValue(); 50 | $this->stack->push($value); 51 | return $last; 52 | } 53 | } 54 | 55 | public function pop() 56 | { 57 | return $this->stack->pop(); 58 | } 59 | 60 | public function isEmpty() 61 | { 62 | return $this->stack->isEmpty(); 63 | } 64 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackReverse/ReverseStackExample.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once "ReverseStack.php"; 10 | 11 | $testData = [1, 2, 3, 4, 5]; 12 | $reverseStack = new \PHPCodes\InterestingQuestion\Stack\StackReverse\ReverseStack($testData); 13 | 14 | while (!$reverseStack->isEmpty()) { 15 | var_dump($reverseStack->pop()); 16 | } 17 | 18 | -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/AbstractMyStack.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\InterestingQuestion\Stack\StackWithGetMin; 10 | 11 | 12 | abstract class AbstractMyStack 13 | { 14 | abstract public function push($value); 15 | 16 | abstract public function pop(); 17 | 18 | abstract public function getMin(); 19 | 20 | abstract public function isEmpty(); 21 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/MyStack.php: -------------------------------------------------------------------------------- 1 | 8 | * @copyright liu hao 9 | * 10 | * 题目:实现一个特殊的栈,在实现栈基本功能的基础上,实现返回栈中最小元素的操作. 11 | * 12 | * 要求: 13 | * 1.pop,push,getMin操作的时间复杂度为O(1) 14 | * 2.可使用现成的栈结构 15 | */ 16 | 17 | class MyStack extends AbstractMyStack 18 | { 19 | /** 20 | * @var null|\SplStack 21 | */ 22 | private $dataStack = null; 23 | 24 | /** 25 | * @var null|\SplStack 26 | */ 27 | private $minStack = null; 28 | 29 | public function __construct() 30 | { 31 | $this->dataStack = new \SplStack(); 32 | $this->minStack = new \SplStack(); 33 | } 34 | 35 | public function push($value) 36 | { 37 | if (!$this->minStack->isEmpty()) { 38 | $currentMin = $this->minStack->top(); 39 | if ($currentMin > $value) { 40 | $this->minStack->push($value); 41 | } 42 | } else { 43 | $this->minStack->push($value); 44 | } 45 | 46 | $this->dataStack->push($value); 47 | } 48 | 49 | public function pop() 50 | { 51 | 52 | if ($this->dataStack->isEmpty()) { 53 | throw new \RuntimeException("栈为空"); 54 | } 55 | 56 | $value = $this->dataStack->pop(); 57 | $currentMin = $this->minStack->top(); 58 | if ($value == $currentMin) { 59 | $this->minStack->pop(); 60 | } 61 | 62 | return $value; 63 | } 64 | 65 | public function getMin() 66 | { 67 | if ($this->minStack->isEmpty()) { 68 | throw new \RuntimeException("栈为空"); 69 | } 70 | 71 | $value = $this->minStack->top(); 72 | 73 | return $value; 74 | } 75 | 76 | public function isEmpty() 77 | { 78 | return $this->dataStack->isEmpty(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/MyStackAnother.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\InterestingQuestion\Stack\StackWithGetMin; 10 | 11 | 12 | class MyStackAnother extends AbstractMyStack 13 | { 14 | /** 15 | * @var null|\SplStack 16 | */ 17 | private $dataStack = null; 18 | 19 | /** 20 | * @var null|\SplStack 21 | */ 22 | private $minStack = null; 23 | 24 | public function __construct() 25 | { 26 | $this->dataStack = new \SplStack(); 27 | $this->minStack = new \SplStack(); 28 | } 29 | 30 | 31 | public function push($value) 32 | { 33 | $this->dataStack->push($value); 34 | 35 | if (!$this->minStack->isEmpty()) { 36 | $current = $this->minStack->top(); 37 | if ($current > $value) { 38 | $this->minStack->push($value); 39 | } else { 40 | $this->minStack->push($current); 41 | } 42 | } else { 43 | $this->minStack->push($value); 44 | } 45 | } 46 | 47 | 48 | public function pop() 49 | { 50 | if ($this->dataStack->isEmpty()) { 51 | throw new \RuntimeException("stack is empty"); 52 | } 53 | $value = $this->dataStack->pop(); 54 | $this->minStack->pop(); 55 | 56 | return $value; 57 | } 58 | 59 | public function getMin() 60 | { 61 | if ($this->dataStack->isEmpty()) { 62 | throw new \RuntimeException("stack is empty"); 63 | } 64 | $value = $this->minStack->top(); 65 | 66 | return $value; 67 | } 68 | 69 | public function isEmpty() 70 | { 71 | return $this->dataStack->isEmpty(); 72 | } 73 | 74 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/MyStackAnotherExample.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once "AbstractMyStack.php"; 10 | require_once "MyStackAnother.php"; 11 | 12 | use PHPCodes\InterestingQuestion\Stack\StackWithGetMin\MyStackAnother; 13 | 14 | $dataList = [200, 222, 39, 144, 11, 24]; 15 | 16 | $myStack = new MyStackAnother(); 17 | 18 | foreach ($dataList as $eachValue) { 19 | $myStack->push($eachValue); 20 | var_dump($myStack->getMin()); 21 | } 22 | 23 | echo '
'; 24 | 25 | foreach ($dataList as $value) { 26 | var_dump($myStack->getMin()); 27 | $myStack->pop(); 28 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/MyStackExample.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once "AbstractMyStack.php"; 10 | require_once "MyStack.php"; 11 | 12 | use PHPCodes\InterestingQuestion\Stack\StackWithGetMin\MyStack; 13 | 14 | $dataList = [100, 22, 39, 44, 11, 24]; 15 | 16 | $myStack = new MyStack(); 17 | 18 | foreach ($dataList as $eachValue) { 19 | $myStack->push($eachValue); 20 | var_dump($myStack->getMin()); 21 | } 22 | 23 | echo '
'; 24 | 25 | foreach ($dataList as $value) { 26 | var_dump($myStack->getMin()); 27 | $myStack->pop(); 28 | } -------------------------------------------------------------------------------- /Php/InterestingQuestion/Stack/StackWithGetMin/README.md: -------------------------------------------------------------------------------- 1 | #### 题目 2 | 实现一个特殊的栈,在实现栈基本功能的基础上,实现返回栈中最小元素的操作. 3 | #### 要求: 4 | 1.pop,push,getMin操作的时间复杂度为O(1) 5 | 2.可使用现成的栈结构 6 | 7 | #### 方案一 8 | 类文件:MyStack.php 9 | 示例文件:MyStackExample.php 10 | 11 | 使用两个栈dataStack和minStack. 12 | 13 | push操作: 14 | 假设当前压入栈的值为value. 15 | 将value压入dataStack. 16 | 如果dminStack为空,将value压入这个栈. 17 | 如果minStack不为空,比较minStack栈顶元素和value的大小,如果value小,则压入minStack 18 | 19 | pop操作: 20 | 假设要弹出的dataStack栈顶元素的值为value 21 | 将value弹出dataStack 22 | 如果value和minStack的栈顶元素相同,则弹出minStack栈顶元素 23 | 24 | getMin操作: 25 | 直接返回minStack的栈顶元素 26 | 27 | #### 方案二 28 | 类文件:MyStackAnother.php 29 | 示例文件:MyStackAnotherExample.php 30 | 31 | 使用两个栈dataStack和minStack 32 | 33 | push操作: 34 | 假设当前要压入栈的值为value. 35 | 将value压入dataStack. 36 | 如果minStack为空,将value压入minStack 37 | 如果minStack不为空,若value小于minStack栈顶元素,则压入value,否则再次压入minStack栈顶元素 38 | 39 | pop操作: 40 | 弹出dataStack栈顶元素 41 | 弹出minStack栈顶元素 42 | 43 | getMin操作: 44 | 直接返回minStack栈顶元素 45 | 46 | 47 | #### 两个方案的比较 48 | 方案一空间占用少,pop操作耗时长 49 | 方案二pop操作快,空间占用多 50 | -------------------------------------------------------------------------------- /Php/LaravelTest/README.md: -------------------------------------------------------------------------------- 1 | - MiddleWare : 根据Laravel框架中MiddleWare的实现原理,实现的一个简单demo -------------------------------------------------------------------------------- /Php/LogManagementSystem/README.md: -------------------------------------------------------------------------------- 1 | 日志管理系统简单模型 -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/ArrayReduce.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | class ArrayReduce 10 | { 11 | public function run() 12 | { 13 | return array_reduce([1, 3], function ($carry, $item) { 14 | $carry += $item; 15 | return $carry; 16 | }, 0); 17 | } 18 | } 19 | 20 | $test = new ArrayReduce(); 21 | var_dump($test->run()); -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/FileOperation.php: -------------------------------------------------------------------------------- 1 | $value) { 22 | $this->$key = $value; 23 | } 24 | } 25 | 26 | public function run() 27 | { 28 | try { 29 | $handle = fopen($this->filePath, $this->fileMode); 30 | fseek($handle, -1, SEEK_END); 31 | $contents = ""; 32 | $rowCount = 0; 33 | do { 34 | if (($str = fgetc($handle)) == "\n") { 35 | $rowCount++; 36 | } 37 | $contents = $str.$contents; 38 | if (ftell($handle) == 1) { 39 | break; 40 | } 41 | fseek($handle, -2, SEEK_CUR); 42 | } while ($rowCount < $this->rowNum); 43 | var_export(trim($contents, "\n")); 44 | fclose($handle); 45 | } catch(\Exception $e) { 46 | var_export($e->getMessage()); 47 | } 48 | } 49 | } 50 | 51 | class Test 52 | { 53 | public function run() 54 | { 55 | $filePath = './TestData/GetFileLastNumRow/test.data'; 56 | 57 | $getFileLastNumRow = new GetFileLastNumRow(compact('filePath')); 58 | $getFileLastNumRow->run(); 59 | } 60 | } 61 | 62 | $test = new Test(); 63 | $test->run(); 64 | -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/README.md: -------------------------------------------------------------------------------- 1 | #### php语法测试代码 2 | - TestData : 测试数据 3 | - ThrowableTest : Throwable类测试 4 | - ArrayReduce : array_reduce函数测试 5 | - CloneSyntax : clone语法测试 6 | - FileOperation : 文件操作测试 7 | - GetFileLastNumRow : 或取文件最后一行代码测试 -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/TestData/FileOperation/testA _original.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/Php/PhpSyntaxTestCode/TestData/FileOperation/testA _original.txt -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/TestData/FileOperation/testA.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/2lovecode/code-segment/bb2b6a650809f822873abfd45b7c15a5beb2b0de/Php/PhpSyntaxTestCode/TestData/FileOperation/testA.txt -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/TestData/FileOperation/testB.txt: -------------------------------------------------------------------------------- 1 | 1 zhangsan 2 | 2 lisi 3 | 3 wangwu 4 | 4 zhaoliu -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/TestData/FileOperation/testB_original.txt: -------------------------------------------------------------------------------- 1 | 1 zhangsan 2 | 2 lisi 3 | 3 wangwu 4 | 4 zhaoliu -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/TestData/GetFileLastNumRow/test.data: -------------------------------------------------------------------------------- 1 | line 1 2 | line 2 3 | line 3 4 | line 4 -------------------------------------------------------------------------------- /Php/PhpSyntaxTestCode/ThrowableTest/ThrowableTest.php: -------------------------------------------------------------------------------- 1 | getMessage()); 17 | } 18 | 19 | try { 20 | throw new MyError('This is Error!'); 21 | } catch (Throwable $e) { 22 | var_dump($e->getMessage()); 23 | } 24 | 25 | // try { 26 | // throw new MyClass('Hello World!'); 27 | // } catch (Throwable $e) { 28 | // var_dump($e->getMessage()); 29 | // } -------------------------------------------------------------------------------- /Php/README.md: -------------------------------------------------------------------------------- 1 | #### 注 1):关于示例 2 | 1. 根据建议,在之后的代码中,示例代码所在文件和类的定义文件会分开,但它们会在同一目录下. 3 | 2. 后缀为Example的文件名才是示例,请注意! 4 | 3. 以MyStack.php和以MyStackExample.php为例,前者是类的定义文件,后者是前者类的使用示例. 5 | 4. 之后使用新的组织形式的代码,在当前README文件中会有 [NEW] 标识 6 | 5. 之前的代码,运行示例,直接执行该文件.现在需要执行后缀为Example的文件 7 | 8 | #### 注 2):关于单元测试 9 | 1. 在之后的代码中,我们会考虑加入单元测试,如有需要请阅读下面事项. 10 | 2. 请在根目录,也就是PhpCodes目录的上一级目录执行composer install命令安装依赖库. 11 | 3. 执行单元测试请在当前目录即PhpCodes目录下执行 php vendor/bin/phpunit命令 12 | 4. 单元测试代码放到Tests文件夹中 13 | 5. 同样,有单元测试的,我们会在当前的README文件中打上 [UNITTEST]标识 14 | 15 | #### 目录 16 | 17 | - [AttributesChangeLog](AttributesChangeLog) : 记录参数的一个类,该类实例化的对象可以持有一个参数池,所有出现在这个参数池中的参数都可以跟踪其值的变化. 18 | 19 | - [BloomFilter](BloomFilter) : 布隆过滤器 20 | 21 | - [Container](Container) : 依赖注入容器(DI)的实现(copy from laravel) 22 | 23 | - [DataStructureAndAlgorithm](DataStructureAndAlgorithm) : 数据结构和算法 24 | 25 | - [DesignPatterns](DesignPatterns) : 一些设计模式的示例 26 | 27 | - [FileOperation](FileOperation) : php操作目录和文件的一些示例 28 | 29 | - [FilterSensitiveWord](FilterSensitiveWord) : 敏感词过滤实现 30 | 31 | - [HyperLogLog](HyperLogLog) : 模拟redis的HyperLogLog数据结构 32 | 33 | - [InterestingQuestion](InterestingQuestion) : 一些有趣的需要使用数据结构和算法解决的问题[NEW][UNITTEST] 34 | 35 | - [LaravelTest](LaravelTest) : 仿照Laravel框架中一些机制写的测试代码 36 | 37 | - [PhpSyntaxTestCode](PhpSyntaxTestCode) : 一些php的语法的测试示例 38 | 39 | - [SimpleContainer](SimpleContainer) : DI容器简单实现 40 | 41 | - [SimpleDataBase](SimpleDataBase) : php实现的一个简单的key-value数据库 42 | 43 | - [SimpleRandom](SimpleRandom) : 简单的页面随机抽取实现 44 | 45 | - [Tests](Tests) : 单元测试代码 46 | 47 | - [TransformDataPieces](TransformDataPieces) : 将crontab的配置,例如: * * * * *,分解为散列的时间片段,实现定时功能 48 | 49 | - [UsefulTools](UsefulTools) : 一些有趣的工具 -------------------------------------------------------------------------------- /Php/ReplaceStrTemplate/ReplaceStrTemplate.php: -------------------------------------------------------------------------------- 1 | 'World', 20 | 'value2' => 'Love', 21 | ]; 22 | 23 | public function repalceTemplate() 24 | { 25 | $res = preg_replace_callback( 26 | $this->reg, 27 | function ($matches) { 28 | $value = $matches[0]; 29 | if (isset($matches[1])) { 30 | $index = $matches[1]; 31 | if (isset($this->valueList[$index])) { 32 | $value = $this->valueList[$index]; 33 | } 34 | } 35 | return $value; 36 | }, 37 | $this->strTemplate 38 | ); 39 | 40 | return $res; 41 | } 42 | } 43 | 44 | $a = new ReplaceStrTemplate(); 45 | 46 | var_dump($a->repalceTemplate()); -------------------------------------------------------------------------------- /Php/SimpleContainer/README.md: -------------------------------------------------------------------------------- 1 | #### DI容器简单实现 -------------------------------------------------------------------------------- /Php/SimpleContainer/SimpleContainer.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | class SimpleContainer 10 | { 11 | private $defines = []; 12 | private $instances = []; 13 | 14 | public function set($abstract, $concrete) 15 | { 16 | $this->defines[$abstract] = $concrete; 17 | } 18 | 19 | public function get($abstract) 20 | { 21 | if (isset($this->instances[$abstract])) { 22 | return $this->instances[$abstract]; 23 | } 24 | 25 | $object = null; 26 | if (isset($this->defines[$abstract])) { 27 | $concrete = $this->defines[$abstract]; 28 | $object = $this->build($concrete); 29 | } else { 30 | $object = $this->build($abstract); 31 | } 32 | 33 | $this->instances[$abstract] = $object; 34 | 35 | return $object; 36 | } 37 | 38 | private function build($concrete) 39 | { 40 | $reflector = new ReflectionClass($concrete); 41 | 42 | //如果不能实例化,抛出异常 43 | if (!$reflector->isInstantiable()) { 44 | throw new Exception('class ['.$concrete.'] can not be instantiated!'); 45 | } 46 | 47 | //获取构造函数方法反射对象 48 | $constructor = $reflector->getConstructor(); 49 | 50 | //类不存在构造函数,直接实例化 51 | if (is_null($constructor)) { 52 | return new $concrete; 53 | } 54 | 55 | //给每个签名参数赋值,如果参数是对象则实例化,如果有默认值则赋给默认值 56 | foreach ($constructor->getParameters() as $param) { 57 | if ($param->isDefaultValueAvailable()) { 58 | $dependencies[] = $param->getDefaultValue(); 59 | } else { 60 | $dependClass = $param->getClass(); 61 | $isClass = !is_null($dependClass) ? true : false; 62 | $dependencies[] = $isClass ? $this->get($dependClass->getName()) : null; 63 | } 64 | } 65 | //实例化对象 66 | return $reflector->newInstanceArgs($dependencies); 67 | } 68 | } -------------------------------------------------------------------------------- /Php/SimpleContainer/Usage.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | require_once 'SimpleContainer.php'; 9 | 10 | interface AInterface 11 | { 12 | public function run(); 13 | } 14 | 15 | class A implements AInterface 16 | { 17 | public function run() 18 | { 19 | return 'I am A!'; 20 | } 21 | } 22 | 23 | class B 24 | { 25 | private $example; 26 | 27 | public function __construct(AInterface $example) 28 | { 29 | $this->example = $example; 30 | } 31 | 32 | public function run() 33 | { 34 | $str = $this->example->run(); 35 | return '<<<< '.$str.' >>>>'; 36 | } 37 | } 38 | $container = new SimpleContainer(); 39 | 40 | //示例1 41 | $container->set('AInterface', 'A'); 42 | $a = $container->get('AInterface'); 43 | var_dump($a->run()); 44 | 45 | //示例2 46 | $b = $container->get('B'); 47 | var_dump($b->run()); 48 | -------------------------------------------------------------------------------- /Php/SimpleDataBase/MyDataBase.php: -------------------------------------------------------------------------------- 1 | connect('dbTest'); //数据库连接 12 | * 13 | * $dbHandler->insert('key1', '1111111'); //写入数据,仅支持key-value形式 14 | * 15 | * $dbHandler->find('key1'); //数据查找 16 | * 17 | * $dbHandler->delete('key1'); //删除数据 18 | * 19 | * $db->close(); //关闭数据连接 20 | * 21 | */ 22 | define('DB_INSERT_SUCCESS', 'SUCCESS'); 23 | define('DB_INSERT_FAILED', 'FAILED'); 24 | define('DB_DELETE_SUCCESS', 'SUCCESS'); 25 | define('DB_DELETET_FAILED', 'FAILED'); 26 | define('DB_EXISTS_KEY', 'KEYEXISTS'); 27 | 28 | define('DB_BUCKET_SIZE', 262144); //这里定义的是Hash表中链表的长度 29 | define('DB_KEY_SIZE', 128); //存储key值的大小 30 | define('DB_INDEX_SIZE', DB_KEY_SIZE + 12); //定义了一个索引节点的长度,一个索引节点包括: 4字节的指向下一索引节点值 + 128字节的Key值 + 4字节的数据在数据文件的偏移值 + 4字节的数据长度值 31 | 32 | include './DataBaseObject.php'; 33 | 34 | class MyDataBase 35 | { 36 | private $dataHandler; 37 | private $indexHandler; 38 | private $closeFlag = false; 39 | 40 | public function connect($databaseName) 41 | { 42 | try { 43 | 44 | $indexFile = './index/'.$databaseName.'.inx'; 45 | $dataFile = './data/'.$databaseName.'.dat'; 46 | 47 | $needInit = false; 48 | 49 | if (!file_exists($indexFile)) { 50 | $openModel = 'w+b'; 51 | $needInit = true; 52 | } else { 53 | $openModel = 'r+b'; 54 | } 55 | 56 | $this->indexHandler = fopen($indexFile, $openModel); 57 | 58 | //初始化索引文件,用0初始化。 59 | if ($needInit) { 60 | $initValue = pack('L', 0x00000000); 61 | for ($i = 0; $i < DB_BUCKET_SIZE; $i++) { 62 | fwrite($this->indexHandler, $initValue, 4); 63 | } 64 | } 65 | 66 | $this->dataHandler = fopen($dataFile, $openModel); 67 | 68 | $dataBase = new DataBaseObject($this->dataHandler, $this->indexHandler); 69 | 70 | } catch (Exception $e) { 71 | return NULL; 72 | } 73 | return $dataBase; 74 | } 75 | 76 | public function close() 77 | { 78 | try { 79 | if (!$this->closeFlag) { 80 | fclose($this->dataHandler); 81 | fclose($this->indexHandler); 82 | $this->closeFlag = true; 83 | } 84 | } catch (Exception $e) { 85 | return false; 86 | } 87 | return true; 88 | } 89 | } 90 | 91 | //下面是使用示例 92 | $db = new MyDataBase(); 93 | 94 | $dbHandler = $db->connect('dbTest'); 95 | 96 | $dbHandler->insert('key1', '1111111'); 97 | var_dump($dbHandler->find('key1')); 98 | 99 | $dbHandler->delete('key1'); 100 | var_dump($dbHandler->find('key1')); 101 | 102 | 103 | $db->close(); -------------------------------------------------------------------------------- /Php/SimpleDataBase/README.md: -------------------------------------------------------------------------------- 1 | #### 简单key-value数据库实现 -------------------------------------------------------------------------------- /Php/SimpleDataBase/data/dbTest.dat: -------------------------------------------------------------------------------- 1 | 111111111111111111111 -------------------------------------------------------------------------------- /Php/SimpleRandom/App/AbstractApp.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace App; 10 | 11 | 12 | abstract class AbstractApp 13 | { 14 | abstract public function index(); 15 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/App/Welcome.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace App; 10 | 11 | 12 | use Service\Random; 13 | 14 | class Welcome extends AbstractApp 15 | { 16 | public function index() 17 | { 18 | $random = new Random(); 19 | $random->setList(['c', 'php', 'go', 'java']); 20 | return $random->exec(); 21 | } 22 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Http/Request.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright liu hao 8 | */ 9 | 10 | class Request 11 | { 12 | public $identifier = "p"; 13 | 14 | public $queryParams = null; 15 | 16 | public function getQueryParams() 17 | { 18 | if (is_null($this->queryParams)) { 19 | $this->queryParams = $_GET; 20 | } 21 | 22 | return $this->queryParams; 23 | } 24 | 25 | public function getRoute() 26 | { 27 | $route = ['welcome', 'index']; 28 | 29 | if (isset($this->queryParams[$this->identifier])) { 30 | $value = $this->queryParams[$this->identifier]; 31 | 32 | $route = explode('/', $value); 33 | 34 | if (count($route) === 1) { 35 | $route[] = 'index'; 36 | } 37 | } 38 | 39 | return $route; 40 | } 41 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Http/Response.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright liu hao 8 | */ 9 | 10 | class Response 11 | { 12 | public $content; 13 | 14 | public function setContent($content = "") 15 | { 16 | $this->content = $content; 17 | } 18 | public function send() 19 | { 20 | echo $this->content; 21 | } 22 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Service/Dispatch.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace Service; 10 | 11 | 12 | use Tools\ObjectSet; 13 | use Tools\StrTool; 14 | 15 | class Dispatch 16 | { 17 | public $route = []; 18 | 19 | public function __construct() 20 | { 21 | $request = ObjectSet::$request; 22 | $this->route = $request->getRoute(); 23 | } 24 | 25 | public function dispatch() 26 | { 27 | $route = $this->route; 28 | 29 | $action = array_pop($route); 30 | 31 | $tmp = array_map(function ($value) { 32 | return StrTool::underscore2camel($value); 33 | }, $route); 34 | 35 | $class = '\\App\\'.implode('\\', $tmp); 36 | 37 | if (class_exists($class)) { 38 | $app = new $class(); 39 | if (method_exists($app, $action)) { 40 | $result = $app->$action(); 41 | $response = ObjectSet::$response; 42 | $response->setContent($result); 43 | } else { 44 | throw new \Exception('method ['.$action.']not exists in class ['.$class.']!'); 45 | } 46 | } else { 47 | throw new \Exception('class ['.$class.']not exists!'); 48 | } 49 | 50 | } 51 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Service/Random.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace Service; 10 | 11 | 12 | class Random 13 | { 14 | public $list = []; 15 | 16 | public function exec() 17 | { 18 | $key = array_rand($this->list, 1); 19 | return $this->list[$key]; 20 | } 21 | 22 | public function setList(array $list = []) 23 | { 24 | $this->list = $list; 25 | } 26 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Tools/ObjectSet.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace Tools; 10 | 11 | 12 | use Http\Request; 13 | use Http\Response; 14 | 15 | class ObjectSet 16 | { 17 | /** 18 | * @var Request 19 | */ 20 | public static $request = null; 21 | 22 | /** 23 | * @var Response 24 | */ 25 | public static $response = null; 26 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/Tools/StrTool.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace Tools; 10 | 11 | 12 | class StrTool 13 | { 14 | public static function underscore2camel($str) 15 | { 16 | $list = explode('_', $str); 17 | 18 | foreach ($list as $key => $value) { 19 | if (!empty($value)) { 20 | $list[$key] = ucfirst($value); 21 | } else { 22 | unset($list[$key]); 23 | } 24 | } 25 | 26 | return implode("", $list); 27 | } 28 | 29 | // public static function camel2underscore($str) 30 | // { 31 | // } 32 | } -------------------------------------------------------------------------------- /Php/SimpleRandom/autoload.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | function _autoload($className) 10 | { 11 | $filePath = str_replace('\\', DIRECTORY_SEPARATOR, $className).'.php'; 12 | include $filePath; 13 | } 14 | 15 | spl_autoload_register('_autoload'); -------------------------------------------------------------------------------- /Php/SimpleRandom/index.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | require_once './autoload.php'; 10 | 11 | \Tools\ObjectSet::$request = new \Http\Request(); 12 | \Tools\ObjectSet::$response = new \Http\Response(); 13 | 14 | $dispatch = new \Service\Dispatch(); 15 | 16 | $dispatch->dispatch(); 17 | 18 | \Tools\ObjectSet::$response->send(); -------------------------------------------------------------------------------- /Php/Sudoku/Sudoku.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | class Sudoku 10 | { 11 | public function run() 12 | { 13 | $sudo = []; 14 | 15 | for ($i = 0; $i < 9; $i++) { 16 | for ($j = 0; $j < 9; $j++) { 17 | $tmp = 0; 18 | for ($z = 1; $z <= 9; $z++) { 19 | $flag = true; 20 | for ($a = 0; $a <= $i; $a++) { 21 | for ($b = 0; $b <= $j; $b++) { 22 | if ($a != $i && $b != $j) { 23 | if ($sudo[$a][$b] == $z) { 24 | $flag = false; 25 | break 2; 26 | } 27 | } 28 | } 29 | } 30 | if ($flag) { 31 | break; 32 | } else { 33 | continue; 34 | } 35 | } 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Php/Tests/BaseTestCase.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | use PHPUnit\Framework\TestCase; 10 | 11 | class BaseTestCase extends TestCase 12 | { 13 | 14 | } -------------------------------------------------------------------------------- /Php/Tests/InterestingQuestion/Stack/ImplementQueueWithTwoStack/QueueTest.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\Tests\InterestingQuestion\Stack\ImplementQueueWithTwoStack; 10 | 11 | 12 | use PHPCodes\InterestingQuestion\Stack\ImplementQueueWithTwoStack\Queue; 13 | 14 | class QueueTest extends \BaseTestCase 15 | { 16 | public function testIsEmpty() 17 | { 18 | $queue = new Queue(); 19 | 20 | $this->assertTrue($queue->isEmpty()); 21 | 22 | return $queue; 23 | } 24 | 25 | /** 26 | * @param Queue $queue 27 | * @return Queue 28 | * 29 | * @depends testIsEmpty 30 | */ 31 | public function testAdd(Queue $queue) 32 | { 33 | $data = ['a', 'b', 1, 2]; 34 | 35 | foreach ($data as $value) { 36 | $queue->add($value); 37 | } 38 | 39 | $this->assertTrue(!$queue->isEmpty()); 40 | return $queue; 41 | } 42 | 43 | /** 44 | * @param Queue $queue 45 | * @throws \Exception 46 | * 47 | * @depends testIsEmpty 48 | */ 49 | public function testPollAndPeek(Queue $queue) 50 | { 51 | $this->assertEquals('a', $queue->poll()); 52 | $this->assertEquals('b', $queue->peek()); 53 | } 54 | } -------------------------------------------------------------------------------- /Php/Tests/InterestingQuestion/Stack/StackReverse/StackReverseTest.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\Tests\InterestingQuestion\Stack\StackReverse; 10 | 11 | 12 | use PHPCodes\InterestingQuestion\Stack\StackReverse\ReverseStack; 13 | 14 | class StackReverseTest extends \BaseTestCase 15 | { 16 | public function testIsEmpty() 17 | { 18 | $list = [1, 2, 3, 4, 5]; 19 | 20 | $stack = new ReverseStack($list); 21 | 22 | $this->assertTrue(!$stack->isEmpty()); 23 | return $stack; 24 | } 25 | 26 | /** 27 | * @param $expect 28 | * @param ReverseStack $stack 29 | * 30 | * @dataProvider popProvider 31 | * @depends testIsEmpty 32 | */ 33 | public function testPop($expect, ReverseStack $stack) 34 | { 35 | $actual = $stack->pop(); 36 | $this->assertEquals($expect, $actual); 37 | } 38 | 39 | public function popProvider() 40 | { 41 | return [ 42 | 'one' => [1], 43 | 'two' => [2], 44 | 'three' => [3], 45 | 'four' => [4], 46 | 'five' => [5], 47 | ]; 48 | } 49 | } -------------------------------------------------------------------------------- /Php/Tests/InterestingQuestion/Stack/StackWithGetMin/MyStackAnotherTest.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | 9 | namespace PHPCodes\Tests\InterestingQuestion\Stack\StackWithGetMin; 10 | 11 | 12 | use PHPCodes\InterestingQuestion\Stack\StackWithGetMin\MyStackAnother; 13 | 14 | class MyStackAnotherTest extends \BaseTestCase 15 | { 16 | public function testIsEmpty() 17 | { 18 | $myStack = new MyStackAnother(); 19 | $this->assertTrue($myStack->isEmpty()); 20 | 21 | return $myStack; 22 | } 23 | 24 | /** 25 | * @param $value 26 | * @param $except 27 | * @param MyStackAnother $myStack 28 | * 29 | * @dataProvider pushProvider 30 | * @depends testIsEmpty 31 | */ 32 | public function testPushAndGetMin($value, $except, MyStackAnother $myStack) 33 | { 34 | $myStack->push($value); 35 | $this->assertEquals($except, $myStack->getMin()); 36 | } 37 | 38 | public function pushProvider() 39 | { 40 | return [ 41 | 'one' => [111, 111], 42 | 'two' => [222, 111], 43 | 'three' => [33, 33], 44 | 'four' => [44, 33] 45 | ]; 46 | } 47 | 48 | /** 49 | * @param $value 50 | * @param $except 51 | * @param MyStackAnother $myStack 52 | * 53 | * @dataProvider popProvider 54 | * @depends testIsEmpty 55 | * @depends testPushAndGetMin 56 | */ 57 | public function testPopAndGetMin($value, $except, MyStackAnother $myStack) 58 | { 59 | $this->assertEquals($except, $myStack->getMin()); 60 | $current = $myStack->pop(); 61 | $this->assertEquals($value, $current); 62 | } 63 | 64 | public function popProvider() 65 | { 66 | return [ 67 | 'one' => [44, 33], 68 | 'two' => [33, 33], 69 | 'three' => [222, 111], 70 | 'four' => [111, 111] 71 | ]; 72 | } 73 | } -------------------------------------------------------------------------------- /Php/Tests/InterestingQuestion/Stack/StackWithGetMin/MyStackTest.php: -------------------------------------------------------------------------------- 1 | 6 | * @copyright liu hao 7 | */ 8 | use PHPCodes\InterestingQuestion\Stack\StackWithGetMin\MyStack; 9 | 10 | class MyStackTest extends BaseTestCase 11 | { 12 | 13 | public function testIsEmpty() 14 | { 15 | $myStack = new MyStack(); 16 | 17 | $this->assertTrue($myStack->isEmpty()); 18 | 19 | return $myStack; 20 | } 21 | 22 | /** 23 | * @param $value 24 | * @param $result 25 | * @param MyStack $myStack 26 | * @dataProvider pushAndGetMinProvider 27 | * @depends testIsEmpty 28 | */ 29 | public function testPushAndGetMin($value, $result, MyStack $myStack) 30 | { 31 | $myStack->push($value); 32 | $this->assertEquals($result, $myStack->getMin()); 33 | } 34 | 35 | public function pushAndGetMinProvider() 36 | { 37 | return [ 38 | 'one' => [200, 200], 39 | 'two' => [150, 150], 40 | 'three' => [165, 150], 41 | 'four' => [22, 22], 42 | 'five' => [34, 22], 43 | 'six' => [11, 11], 44 | ]; 45 | } 46 | 47 | /** 48 | * @param $myStack 49 | * @param $expect 50 | * @param $value 51 | * @dataProvider popAndGetMinProvider 52 | * @depends testIsEmpty 53 | * @depends testPushAndGetMin 54 | */ 55 | public function testPopAndGetMin($expect, $value, MyStack $myStack) 56 | { 57 | $this->assertEquals($expect, $myStack->getMin()); 58 | $current = $myStack->pop(); 59 | $this->assertEquals($value, $current); 60 | } 61 | 62 | public function popAndGetMinProvider() 63 | { 64 | return [ 65 | 'one' => [11, 11], 66 | 'two' => [22, 34], 67 | 'three' => [22, 22], 68 | 'four' => [150, 165], 69 | 'five' => [150, 150], 70 | 'six' => [200, 200] 71 | ]; 72 | } 73 | } -------------------------------------------------------------------------------- /Php/Tests/bootstrap.php: -------------------------------------------------------------------------------- 1 | arr = $arr; 11 | } 12 | 13 | public function run() 14 | { 15 | foreach ($this->arr as $key => $value) { 16 | if (!empty($value) && is_string($value)) { 17 | $this->result = $this->result.sprintf("[\"%s\"]\r\none = \"%s\"\r\nother = \"%s\"\r\n", $key, $value, $value); 18 | } 19 | } 20 | 21 | echo $this->result; 22 | } 23 | } 24 | 25 | $a2t = new Array2Toml(); 26 | $a2t->run(); -------------------------------------------------------------------------------- /Php/UrlShortener/README.md: -------------------------------------------------------------------------------- 1 | #### 缩短url的方式 2 | 3 | AutoIncreaseShortener : 自增序列法 4 | Md5Shortener : 摘要算法 5 | 6 | -------------------------------------------------------------------------------- /Php/UsefulTools/ListFilesAndDirectories/List.php: -------------------------------------------------------------------------------- 1 | getArgs(); 20 | 21 | 22 | } 23 | } 24 | 25 | $list = new MockList(); 26 | $list->run(); -------------------------------------------------------------------------------- /Php/UsefulTools/ListFilesAndDirectories/README.md: -------------------------------------------------------------------------------- 1 | ####功能:列出指定目录中的文件和目录,类似linux的ls命令 -------------------------------------------------------------------------------- /Php/UsefulTools/README.md: -------------------------------------------------------------------------------- 1 | ###使用php写的一些命令行实用工具 2 | 3 | #####1.使用php-cli模式执行 4 | #####2.一些是仿照linux命令的模仿作品 -------------------------------------------------------------------------------- /Php/UsefulTools/TransformStringToKeyValueArray/README.md: -------------------------------------------------------------------------------- 1 | ####把特定形式的字符串转化为key-value数组,默认的分隔符是',',默认的key-value分隔符是':' 2 | 3 | ``` 4 | 例如:字符串是"key1:value1,key2:value2,key3:value3",会转化为['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'] 5 | 6 | ``` -------------------------------------------------------------------------------- /Php/UsefulTools/TransformStringToKeyValueArray/Transform.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Tests 5 | 6 | 7 | -------------------------------------------------------------------------------- /ResourceCollection/Resource.md: -------------------------------------------------------------------------------- 1 | #### 各大学课程资料汇总 2 | 3 | 1. [浙江大学](https://github.com/QSCTech/zju-icicles) 4 | - 链接:https://github.com/QSCTech/zju-icicles 5 | 6 | 2. [上海交大](https://github.com/CoolPhilChen/SJTU-Courses) 7 | - 链接:https://github.com/CoolPhilChen/SJTU-Courses 8 | 9 | 3. [北京大学](https://github.com/lib-pku/libpku) 10 | - 链接:https://github.com/lib-pku/libpku 11 | 12 | 4. [中国科学技术大学](https://github.com/USTC-Resource/USTC-Course) 13 | - 链接 : https://github.com/USTC-Resource/USTC-Course 14 | 15 | --- 16 | 17 | #### 找工作注意事项 18 | 1. [互联网公司黑名单](https://github.com/shengxinjing/programmer-job-blacklist) 19 | - 链接:https://github.com/shengxinjing/programmer-job-blacklist 20 | -------------------------------------------------------------------------------- /Shell/README.md: -------------------------------------------------------------------------------- 1 | #### 一些shell脚本 2 | 3 | - AutoConfigLnmpWebSite : 自动配置lnmp环境站点 -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name" : "2lovecode/code-segment", 3 | "description" : "a collection of code", 4 | "type" : "library", 5 | "license" : [ 6 | "GPL-3.0+" 7 | ], 8 | "authors": [ 9 | { 10 | "name": "liu hao", 11 | "email": "liu546hao@163.com", 12 | "homepage": "http://blog.csdn.net/AIkiller", 13 | "role": "Developer" 14 | } 15 | ], 16 | "require":{ 17 | "php": ">=7.1.0" 18 | }, 19 | "require-dev":{ 20 | "phpunit/phpunit": ">=6.5" 21 | }, 22 | "autoload": { 23 | "psr-4":{ 24 | "PHPCodes\\":"./PhpCodes" 25 | } 26 | }, 27 | "config" : { 28 | "vendor-dir" : "./PhpCodes/vendor" 29 | } 30 | } --------------------------------------------------------------------------------