Skip to content

Commit

Permalink
日常更新
Browse files Browse the repository at this point in the history
  • Loading branch information
6boris committed Dec 27, 2018
1 parent 1e222d7 commit 80ea75b
Show file tree
Hide file tree
Showing 12 changed files with 371 additions and 111 deletions.
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -12,5 +12,6 @@
*.out

.idea/
.vscode/
.orig/
coverage.txt
Empty file added SOLUTIONS.md
Empty file.
1 change: 0 additions & 1 deletion cmd/leetcode.go

This file was deleted.

113 changes: 113 additions & 0 deletions cmd/leetcode/makedir.go
@@ -0,0 +1,113 @@
package leetcode

import (
"fmt"
"io"
"log"
"os"
)

const SOLUTIONS_APTH = "solutions/"
const SOURCE_SOLUTION_FILE_PATH = "cmd/template/solution/solution.go"
const SOURCE_SOLUTION_TEST_FILE_PATH = "cmd/template/solution/solution_test.go"
const SOURCE_SOLUTION_README_FILE_PATH = "cmd/template/solution/README.md"

// 生成木目录Dir
func MakeDir(problems []Problem) {
for i := 0; i < len(problems); i++ {
//fmt.Println(problems[i].PathName)
log.Printf("~~ 开始生成第 %d 题的文件夹 ~~", problems[i].Stat.FrontendQuestionID)

// 检查数据
if problems[i].Stat.QuestionID == 0 {
log.Printf("%d 号题不存,请核查题号。", problems[i].Stat.FrontendQuestionID)
}

if problems[i].PaidOnly {
log.Printf("%d 号题需要付费。如果已经订阅,请注释掉本代码。", problems[i].Stat.FrontendQuestionID)
}

if is_DirExists, _ := PathExists(SOLUTIONS_APTH + problems[i].PathName); is_DirExists {
log.Println("目录已经存在:", SOLUTIONS_APTH+problems[i].PathName)
} else {
err := os.Mkdir(SOLUTIONS_APTH+problems[i].PathName, os.ModePerm)
if err != nil {
log.Printf("目录创建失败", err.Error())
} else {
// 复制文件
log.Println("开始复制文件:")
copy(SOURCE_SOLUTION_FILE_PATH, SOLUTIONS_APTH+problems[i].PathName+"/solution.go")
copy(SOURCE_SOLUTION_TEST_FILE_PATH, SOLUTIONS_APTH+problems[i].PathName+"/solution_test.go")
}
}

}
}

//拷贝文件 要拷贝的文件路径 拷贝到哪里
func copyFile(source, dest string) bool {
if source == "" || dest == "" {
log.Println("source or dest is null")
return false
}
//打开文件资源
source_open, err := os.Open(source)
//养成好习惯。操作文件时候记得添加 defer 关闭文件资源代码
if err != nil {
log.Println(err.Error())
return false
}
defer source_open.Close()
//只写模式打开文件 如果文件不存在进行创建 并赋予 644的权限。详情查看linux 权限解释
dest_open, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 644)
if err != nil {
log.Println(err.Error())
return false
}
//养成好习惯。操作文件时候记得添加 defer 关闭文件资源代码
defer dest_open.Close()
//进行数据拷贝
_, copy_err := io.Copy(dest_open, source_open)
if copy_err != nil {
log.Println(copy_err.Error())
return false
} else {
return true
}
}

func copy(src, dst string) (int64, error) {
sourceFileStat, err := os.Stat(src)
if err != nil {
return 0, err
}

if !sourceFileStat.Mode().IsRegular() {
return 0, fmt.Errorf("%s is not a regular file", src)
}

source, err := os.Open(src)
if err != nil {
return 0, err
}
defer source.Close()

destination, err := os.Create(dst)
if err != nil {
return 0, err
}
defer destination.Close()
nBytes, err := io.Copy(destination, source)
return nBytes, err
}

func PathExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
16 changes: 16 additions & 0 deletions cmd/leetcode/problem-readme.go
@@ -0,0 +1,16 @@
package leetcode

import (
"fmt"
"io/ioutil"
"log"
)

func GetReadmeTemplateBuffer() string {
data, err := ioutil.ReadFile(SOURCE_SOLUTION_README_FILE_PATH)
if err != nil {
log.Panicln("读取 README模板失败", err.Error())
}
fmt.Println(string(data))
return string(data)
}
140 changes: 140 additions & 0 deletions cmd/leetcode/problem.go
@@ -0,0 +1,140 @@
package leetcode

import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)

type LeetCode struct {
UserName string `json:"user_name"`
NumSolved int `json:"num_solved"`
NumTotal int `json:"num_total"`
AcEasy int `json:"ac_easy"`
AcMedium int `json:"ac_medium"`
AcHard int `json:"ac_hard"`
StatStatusPairs []Problem `json:"stat_status_pairs"`
FrequencyHigh int `json:"frequency_high"`
FrequencyMid int `json:"frequency_mid"`
CategorySlug string `json:"category_slug"`
}

// 问题
type Problem struct {
Stat Stat `json:"stat"`
Status bool `json:"status"`
Difficulty Difficulty `json:"difficulty"`
PaidOnly bool `json:"paid_only"`
IsFavor bool `json:"is_favor"`
Frequency int `json:"frequency"`
Progress int `json:"progress"`
PathName string `json:"path_name"`
}
type Stat struct {
QuestionID int `json:"question_id"`
QuestionArticleLive bool `json:"question__article__live"`
QuestionArticleSlug string `json:"question__article__slug"`
QuestionTitle string `json:"question__title"`
QuestionTitleSlup string `json:"question__title_slug"`
QuestionHide bool `json:"question__hide"`
TotalAcs int `json:"total_acs"`
TotalSubmitted int `json:"total_submitted"`
FrontendQuestionID int `json:"frontend_question_id"`
IsNewQuestion bool `json:"is_new_question"`
}

type Difficulty struct {
Level int `json:"level"`
}

func GetAllProblemsPath() []string {
problems := GetProblemsInstance()

res := []string{}
time.Sleep(time.Second)

for i, _ := range problems {
res = append(res, problems[i].PathName)
//fmt.Println(problems[i].Stat.QuestionTitle)
}
return res
}

func GetProblemsInstance() []Problem {

leetcode := new(LeetCode)
Problemsbuffer := getProblemsBuffer()

if err := json.Unmarshal(Problemsbuffer, leetcode); err != nil {
log.Panicf("Json 转换失败: %s\n", err.Error())
}

for i := 0; i < len(leetcode.StatStatusPairs); i++ {
leetcode.StatStatusPairs[i].PathName = string(formatId(leetcode.StatStatusPairs[i].Stat.FrontendQuestionID)) + "." +
formatName(leetcode.StatStatusPairs[i].Stat.QuestionTitle)
}

return leetcode.StatStatusPairs
}

func GetProblemsJosn() string {
problems := GetProblemsInstance()
problem_string, err := json.MarshalIndent(problems, " ", " ")
if err != nil {
log.Fatalln("Problem Json 序列化失败: ", err.Error())
}

return string(problem_string)
}

// 获取题目Buffer
func getProblemsBuffer() []byte {
request, err := http.Get("https://leetcode.com/api/problems/Algorithms/")

if err != nil {
log.Panicln("Lettcode Problem 接口获取失败:", err)
}

if request.StatusCode != 200 {
log.Panicln("Lettcode Problem 接口地址不存在:", err)
}

body, _ := ioutil.ReadAll(request.Body)
return body
}

// 格式化ID 补齐0
func formatId(id int) string {
strId := strconv.Itoa(id)

if len(strId) == 1 {
strId = "000" + strId
}
if len(strId) == 2 {
strId = "00" + strId
}
if len(strId) == 3 {
strId = "0" + strId
}

return strId
}

// 格式化提名称
func formatName(name string) string {
str := ""
for _, v := range name {
if v == ' ' {
str = str + "-"
continue
}
if v == '(' || v == ')' {
continue
}
str = str + string(v)
}
return str
}
23 changes: 22 additions & 1 deletion cmd/main.go
@@ -1 +1,22 @@
package cmd
package main

import (
"fmt"
"github.com/kylesliu/awesome-golang-leetcode/cmd/leetcode"
)

func main() {
problems := leetcode.GetProblemsInstance()

for _, v := range problems {
if v.PaidOnly {

fmt.Println(v)
}
}
// 生成Problem 目录
leetcode.MakeDir(problems)

leetcode.GetReadmeTemplateBuffer()

}
29 changes: 0 additions & 29 deletions cmd/problem.go

This file was deleted.

40 changes: 40 additions & 0 deletions cmd/template/solution/README.md
@@ -0,0 +1,40 @@
# [8. String to Integer (atoi)][title]

## Description
Solution test description ...

**Note:**

**Example 1:**

```
Input: true
Output: true
```
**Example 2:**

```
Input: false
Output: false
```

**Tags:** Array, String

## 题意
> Test solution title mean
## 题解

### 思路1
> test solution description
```go

```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-leetcode][me]

[title]: https://leetcode.com/problems/two-sum
[me]: https://github.com/kylesliu/awesome-golang-leetcode
9 changes: 9 additions & 0 deletions cmd/template/solution/solution.go
@@ -0,0 +1,9 @@
package solution

// Example Solution file
func Solution(bool2 bool) bool {
if bool2 {
return true
}
return false
}

0 comments on commit 80ea75b

Please sign in to comment.