├── .gitignore
├── .vscode
└── launch.json
├── LICENSE
├── Minesweeper
├── index.html
└── scripts
│ ├── sketch.js
│ └── tile.js
├── README.md
├── Sudoku
├── index.html
└── scripts
│ ├── board.js
│ ├── builder.js
│ ├── cell.js
│ ├── sketch.js
│ └── solver.js
├── codeforces
└── DreamoonAndWifi.js
├── codewars
└── pyramid.js
├── favicon.ico
├── index.html
├── leetcode
├── IslandPerimeter.js
├── IslandPerimeter2.js
├── NimGame.js
├── addtwonumbers.js
├── atoi.js
├── fizzbuzz.js
├── hammingdistance.js
├── keyboardRow.js
├── longestAbsoluteFilePath.js
├── longestSubstringWithDistinctCharacters.js
├── longestcommonprefix.js
├── longestpalindromicsubstring.js
├── longestsubstringwithoutrepeatingcharacters.js
├── nextpermutation.js
├── numbercomplement.cs
├── numbersDisappearingFromArray.js
├── permutations.js
├── removenthnode.js
├── searchforrange.js
├── threesum.js
├── threesumclosest.js
└── twosums.js
├── pong
├── index.html
└── scripts
│ ├── ball.js
│ ├── board.js
│ └── sketch.js
├── project.json
└── project.lock.json
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | bin
3 | obj
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible Node.js debug attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "type": "node",
9 | "request": "launch",
10 | "name": "Launch Program",
11 | "program": "${workspaceRoot}/leetcode/longestsubstringwithoutrepeatingcharacters.js",
12 | "cwd": "${workspaceRoot}"
13 | },
14 | {
15 | "type": "node",
16 | "request": "attach",
17 | "name": "Attach to Process",
18 | "port": 5858
19 | }
20 | ]
21 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2016 Mohamed Elsherif
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/Minesweeper/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Minesweeper!
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Minesweeper/scripts/sketch.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var N = 15;
4 | var tiles = [];
5 | var tileSize = 55;
6 | var odds = 0.2;
7 | var totalBombs = 0;
8 | var totalNotVisited = N * N;
9 | var died = false;
10 | var bombsPlaced = false;
11 |
12 | function setup() {
13 | for(var x = 0; x< N; x++) {
14 | tiles[x] = [];
15 | for(var y = 0; y= 1) {
93 | neighbours.push(tiles[x - 1][y])
94 | if( y >= 1) {
95 | neighbours.push(tiles[x - 1][y - 1])
96 | }
97 | }
98 |
99 | if(x <= N - 2) {
100 | neighbours.push(tiles[x + 1][y])
101 | if(y <= N - 2) {
102 | neighbours.push(tiles[x + 1][y + 1])
103 | }
104 | }
105 |
106 | if(y >= 1) {
107 | neighbours.push(tiles[x][y - 1])
108 | if(x <= N - 2){
109 | neighbours.push(tiles[x + 1][y - 1])
110 | }
111 | }
112 |
113 | if(y <= N - 2){
114 | neighbours.push(tiles[x][y + 1])
115 | if(x >= 1) {
116 | neighbours.push(tiles[x - 1][y + 1])
117 | }
118 | }
119 |
120 | return neighbours;
121 | }
122 |
123 | function checkWinOrLose() {
124 | if(died) {
125 | announce("GAME OVER :(", "RED")
126 | return;
127 | }
128 |
129 | if(totalBombs < totalNotVisited){
130 | return;
131 | }
132 |
133 | if(won()) {
134 | announce("You WIN :)", "Green")
135 | }
136 | }
137 |
138 | function won() {
139 | return totalBombs === totalNotVisited;
140 | }
141 |
142 | function gameEnded() {
143 | return won() || died;
144 | }
145 |
146 | function placeBombs(exceptX, exceptY) {
147 | for(var x = 0; x< N; x++) {
148 | for(var y = 0; y 0) {
32 | textAlign(CENTER)
33 | textSize(this.tileSize / 2)
34 | var textColor = this.getTextColor(this.nearBombs)
35 | stroke(textColor)
36 | fill(textColor)
37 | text(this.nearBombs,
38 | this.x * this.tileSize + this.tileSize / 2,
39 | this.y * this.tileSize + 3 * this.tileSize / 4);
40 | }
41 | };
42 |
43 | this.pressed = function() {
44 | if(floor(mouseX / this.tileSize) === this.x && floor(mouseY / this.tileSize) === this.y){
45 | this.clicked = true;
46 | }
47 |
48 | return this.clicked;
49 | };
50 |
51 | this.getTextColor = function(bombs) {
52 | switch(bombs){
53 | case 1:
54 | return "Blue"
55 | case 2:
56 | return "Green"
57 | case 3:
58 | return "Red"
59 | case 4:
60 | return "Navy"
61 | case 5:
62 | return "Darkblue"
63 | case 6:
64 | return "DarkGrey"
65 | default:
66 | return "White"
67 | }
68 | }
69 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Javascript
2 | My JS Playground
3 |
4 |
5 | Nothing fancy, just my playground for trying new libraries and code
6 |
7 |
8 | Minesweeper using p5js: https://bashmohandes.github.io/Javascript/index.html
9 |
10 | PONG using p5js: https://bashmohandes.github.io/Javascript/pong/index.html
11 |
12 | Sudoku using p5js: https://bashmohandes.github.io/Javascript/Sudoku/index.html
13 |
14 | It is also a playground for me solving some leetCode problems in JavaScript.
--------------------------------------------------------------------------------
/Sudoku/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Sudoku!
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/Sudoku/scripts/board.js:
--------------------------------------------------------------------------------
1 | function Board() {
2 |
3 | this.cells = []
4 | this.solutionMode = false
5 | this.solver = new Solver(this)
6 | this.builder = new Builder(this)
7 |
8 | for(var x = 0; x<9; x++) {
9 | this.cells[x] = []
10 | for(var y = 0; y<9; y++) {
11 | this.cells[x][y] = new Cell(x, y)
12 | }
13 | }
14 |
15 |
16 | this.draw = function() {
17 | if(this.solutionMode && !this.solver.finished) {
18 | this.solver.progress()
19 | }
20 |
21 | for(var x = 0; x<9; x++) {
22 | for(var y = 0; y<9; y++) {
23 | this.cells[x][y].valid = this.isValid(x, y)
24 | this.cells[x][y].draw()
25 | }
26 | }
27 | push()
28 | strokeWeight(4)
29 | stroke(0)
30 | for(var i = 0; i<=3; i++) {
31 | line(3 * CELL_SIZE * i, 0, 3 * CELL_SIZE * i, height)
32 | line(0, 3 * CELL_SIZE * i, width, 3 * CELL_SIZE * i)
33 | }
34 | pop()
35 | }
36 |
37 | this.next = function(x, y) {
38 | if(x === 8 && y === 8) {
39 | return [0, 0]
40 | }
41 |
42 | if(x + 1 > 8) {
43 | return [0, y + 1]
44 | }
45 |
46 | return [x + 1, y]
47 | }
48 |
49 | this.isValid = function(x, y) {
50 | for(var i = 0; i<9; i++) {
51 | if(i == y) continue
52 | if(this.cells[x][i].val === this.cells[x][y].val) {
53 | return false
54 | }
55 | }
56 |
57 | for(i = 0; i< 9; i++) {
58 | if(i === x) continue
59 | if(this.cells[i][y].val === this.cells[x][y].val) {
60 | return false
61 | }
62 | }
63 |
64 | var row = Math.floor(x / 3) * 3
65 | var col = Math.floor(y / 3) * 3
66 | for(var i = 0; i< 3; i++) {
67 | for(var j = 0; j< 3; j++) {
68 | var r = i + row
69 | var c = j + col
70 | if(r === x && c === y) continue
71 | if(this.cells[r][c].val === this.cells[x][y].val) {
72 | return false
73 | }
74 | }
75 | }
76 |
77 | return true
78 | }
79 |
80 | this.click = function() {
81 | for(var x = 0; x<9; x++) {
82 | for(var y = 0; y<9; y++) {
83 | if(!this.cells[x][y].fixed) {
84 | this.cells[x][y].click()
85 | }
86 | }
87 | }
88 | }
89 |
90 | this.keyTyped = function() {
91 | for(var x = 0; x<9; x++) {
92 | for(var y = 0; y<9; y++) {
93 | if(this.cells[x][y].selected) {
94 | if(key >= '1' && key <= '9') {
95 | this.cells[x][y].val = Number(key)
96 | }
97 | }
98 | }
99 | }
100 | }
101 |
102 | this.solve = function() {
103 | this.solutionMode = true
104 | }
105 |
106 | this.build = function() {
107 | this.builder.build()
108 | }
109 | }
--------------------------------------------------------------------------------
/Sudoku/scripts/builder.js:
--------------------------------------------------------------------------------
1 | function Builder(board) {
2 | this.board = board
3 |
4 | this.build = function() {
5 | var startX = Math.floor(random(0, 9))
6 | var startY = Math.floor(random(0, 9))
7 | this.board.cells[startX][startY].val = Math.floor(random(1, 10))
8 | var n = this.board.next(startX, startY)
9 | this.buildRec(n[0], n[1], startX, startY)
10 | for(var x = 0; x<9; x++) {
11 | for(var y = 0; y<9; y++) {
12 | if(random() <= DIFFICULTY) {
13 | this.board.cells[x][y].val = undefined
14 | this.board.cells[x][y].fixed = false
15 | }
16 | }
17 | }
18 | }
19 |
20 | this.buildRec = function(x, y, startX, startY) {
21 | for(var i = 1; i<= 9; i++) {
22 | this.board.cells[x][y].val = i
23 | this.board.cells[x][y].fixed = true
24 | if(this.board.isValid(x, y)) {
25 | var n = this.board.next(x, y)
26 | if(n[0] === startX && n[1] === startY) {
27 | return true
28 | }
29 | if(this.buildRec(n[0], n[1], startX, startY)) {
30 | return true
31 | }
32 | }
33 | }
34 |
35 | this.board.cells[x][y].val = undefined
36 | return false
37 | }
38 | }
--------------------------------------------------------------------------------
/Sudoku/scripts/cell.js:
--------------------------------------------------------------------------------
1 | function Cell(x, y) {
2 | this.x = x
3 | this.y = y
4 | this.val = undefined
5 | this.fixed = true
6 | this.selected = false
7 | this.valid = true
8 |
9 |
10 | this.draw = function() {
11 | push()
12 | translate(this.x * CELL_SIZE, this.y * CELL_SIZE)
13 | stroke(0)
14 | if(this.selected) {
15 | fill('LightGrey')
16 | } else {
17 | noFill()
18 | }
19 | rect(0, 0, CELL_SIZE, CELL_SIZE)
20 | textAlign(CENTER)
21 | textSize(this.fixed ? 20 : 40)
22 | if(this.val) {
23 | if(this.fixed) {
24 | fill(0)
25 | } else {
26 | fill(this.valid ? 'BLUE' : 'RED')
27 | }
28 | text(this.val, CELL_SIZE / 2, CELL_SIZE / 2 + (this.fixed ? 10 : 15))
29 | }
30 | pop()
31 | }
32 |
33 | this.click = function() {
34 | if(floor(mouseX / CELL_SIZE) === this.x && floor(mouseY / CELL_SIZE) === this.y){
35 | this.selected = !this.selected;
36 | } else {
37 | this.selected = false
38 | }
39 |
40 | return this.selected;
41 | }
42 | }
--------------------------------------------------------------------------------
/Sudoku/scripts/sketch.js:
--------------------------------------------------------------------------------
1 |
2 | var board
3 | var CELL_SIZE = 70
4 | var DIFFICULTY = 0.4
5 | var slider
6 | function setup() {
7 | var canvas = createCanvas(CELL_SIZE * 9, CELL_SIZE * 9)
8 | canvas.parent("canvas")
9 | board = new Board()
10 | board.build()
11 |
12 | createMenu()
13 | }
14 |
15 | function draw() {
16 | background(255)
17 | DIFFICULTY = slider.value()
18 | board.draw()
19 | }
20 |
21 | function mouseClicked() {
22 | board.click()
23 | }
24 |
25 | function keyTyped() {
26 | board.keyTyped()
27 | }
28 |
29 | function createMenu() {
30 | var d = createDiv("")
31 | var label = createSpan("Difficulty: ")
32 | label.parent(d)
33 | var easy = createSpan("Easy")
34 | easy.parent(d)
35 | slider = createSlider(0.1, 0.6, 0.4, 0.1)
36 | slider.parent(d)
37 | var hard = createSpan("Hard ")
38 | hard.parent(d)
39 | var btn = createButton("Generate")
40 | btn.parent(d)
41 | btn.mousePressed(function(){
42 | board = new Board()
43 | board.build()
44 | })
45 |
46 | var btnSolve = createButton("Auto Solve")
47 | btnSolve.parent(d)
48 | btnSolve.mousePressed(function(){
49 | board.solve()
50 | })
51 | }
--------------------------------------------------------------------------------
/Sudoku/scripts/solver.js:
--------------------------------------------------------------------------------
1 | function Solver(board) {
2 | this.board = board
3 | var stack = []
4 |
5 | function State(x, y, val) {
6 | this.x = x
7 | this.y = y
8 | this.val = val
9 | }
10 |
11 | this.x = 0
12 | this.y = 0
13 | this.val = 1
14 |
15 | this.finished = false
16 |
17 | this.progress = function() {
18 | var isValid = false
19 | if(!this.board.cells[this.x][this.y].fixed) {
20 | this.board.cells[this.x][this.y].val = this.val
21 | if(this.board.isValid(this.x, this.y)) {
22 | isValid = true
23 | stack.push(new State(this.x, this.y, this.val))
24 | this.val = 1
25 | } else {
26 | if(this.val + 1 <= 9) {
27 | this.val ++
28 | return
29 | } else {
30 | this.board.cells[this.x][this.y].val = undefined
31 | if(stack.length > 0) {
32 | var prevState = stack.pop()
33 | this.x = prevState.x
34 | this.y = prevState.y
35 | this.val = prevState.val + 1 > 9 ? undefined : prevState.val + 1
36 | return;
37 | }
38 | }
39 | }
40 | }
41 | if(this.board.cells[this.x][this.y].fixed || isValid) {
42 | var n = this.board.next(this.x, this.y)
43 | this.x = n[0]
44 | this.y = n[1]
45 | this.finished = (this.x === 0 && this.y === 0)
46 | } else {
47 | this.board.cells[this.x][this.y].val = undefined
48 | }
49 | }
50 | }
--------------------------------------------------------------------------------
/codeforces/DreamoonAndWifi.js:
--------------------------------------------------------------------------------
1 | function calculateProb(s1, s2) {
2 | var possibilties = [];
3 | calculatePossibilities(s2, 0, [], possibilties);
4 |
5 | var d = destinationNum(s1);
6 | var successCount = 0;
7 | for(var i = 0; i
2 |
3 |
4 | My JavaScript Projects
5 |
6 |
7 |
8 |
11 |
12 | Pong
13 |
14 |
17 |
18 |
--------------------------------------------------------------------------------
/leetcode/IslandPerimeter.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[][]} grid
3 | * @return {number}
4 | */
5 | var islandPerimeter = function(grid) {
6 | var visited = {}
7 |
8 | for(var i = 0; i < grid.length; i++) {
9 | for(var j = 0; j < grid[0].length; j++) {
10 | if(grid[i][j]) {
11 | return countSides(grid, i, j, visited)
12 | }
13 | }
14 | }
15 |
16 | return 0
17 | };
18 |
19 |
20 | function countSides(grid, i, j, visited) {
21 | console.log(i, j)
22 | var sides = 0
23 | if(visited[i + "," + j]) {
24 | return 0
25 | }
26 |
27 | if(!grid[i][j]) {
28 | return 1
29 | }
30 |
31 | visited[i + "," + j] = true
32 |
33 | if(i - 1 < 0) {
34 | sides ++
35 | } else {
36 | sides += countSides(grid, i - 1, j, visited)
37 | }
38 |
39 | if(i + 1 > grid.length - 1) {
40 | sides ++
41 | } else {
42 | sides += countSides(grid, i + 1, j, visited)
43 | }
44 |
45 | if(j - 1 < 0) {
46 | sides ++
47 | } else {
48 | sides += countSides(grid, i, j - 1, visited)
49 | }
50 |
51 | if(j + 1 > grid[0].length - 1) {
52 | sides ++
53 | } else {
54 | sides += countSides(grid, i, j + 1, visited)
55 | }
56 |
57 | return sides
58 | }
59 |
60 | var input = [[0,1,0,0],
61 | [1,1,1,0],
62 | [0,1,0,0],
63 | [1,1,0,0]]
64 |
65 | console.log(islandPerimeter(input))
--------------------------------------------------------------------------------
/leetcode/IslandPerimeter2.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[][]} grid
3 | * @return {number}
4 | */
5 | var islandPerimeter = function(grid) {
6 | var result = 0
7 | for(var i = 0; i < grid.length; i++) {
8 | for(var j = 0; j < grid[0].length; j++) {
9 | if(!grid[i][j]) {
10 | continue;
11 | }
12 |
13 | if(isWater(grid, i - 1, j)) {
14 | result ++
15 | }
16 |
17 | if(isWater(grid, i + 1, j)) {
18 | result ++
19 | }
20 |
21 | if(isWater(grid, i, j - 1)) {
22 | result ++
23 | }
24 |
25 | if(isWater(grid, i, j + 1)) {
26 | result ++
27 | }
28 | }
29 | }
30 |
31 | return result
32 | };
33 |
34 | function isWater(grid, i, j) {
35 | return i < 0 || i > grid.length - 1 || j < 0 || j > grid[0].length - 1 || !grid[i][j]
36 | }
37 |
38 |
39 | var input = [[0,1,0,0],
40 | [1,1,1,0],
41 | [0,1,0,0],
42 | [1,1,0,0]]
43 |
44 | console.log(islandPerimeter(input))
--------------------------------------------------------------------------------
/leetcode/NimGame.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number} n
3 | * @return {boolean}
4 | */
5 | var canWinNim = function(n) {
6 | return n % 4 !== 0
7 | };
8 |
--------------------------------------------------------------------------------
/leetcode/addtwonumbers.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val) {
4 | * this.val = val;
5 | * this.next = null;
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} l1
10 | * @param {ListNode} l2
11 | * @return {ListNode}
12 | */
13 | var addTwoNumbers = function(l1, l2) {
14 | var c1 = l1, c2 = l2
15 | var carry = 0
16 | var result
17 | var current, prev
18 | while(c1 || c2 || carry) {
19 | var sum = (c1 ? c1.val : 0) + (c2 ? c2.val : 0) + carry
20 | if(!current) {
21 | current = new ListNode(sum % 10)
22 | if(!result) {
23 | result = current
24 | }
25 | if(prev) {
26 | prev.next = current
27 | }
28 | }
29 | carry = Math.floor(sum / 10)
30 | if(c1) {
31 | c1 = c1.next
32 | }
33 | if(c2) {
34 | c2 = c2.next
35 | }
36 | prev = current
37 | current = current.next
38 | }
39 |
40 | return result
41 | };
42 |
43 |
44 | function ListNode(val) {
45 | this.val = val;
46 | this.next = null;
47 | }
48 |
49 | var l1 = new ListNode(2)
50 | l1.next = new ListNode(4)
51 | l1.next.next = new ListNode(3)
52 |
53 |
54 | var l2 = new ListNode(5)
55 | l2.next = new ListNode(6)
56 | l2.next.next = new ListNode(4)
57 |
58 | console.log(addTwoNumbers(l1, l2))
--------------------------------------------------------------------------------
/leetcode/atoi.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string} str
3 | * @return {number}
4 | */
5 | var myAtoi = function(str) {
6 | if(!str || str.length === 0) {
7 | return 0
8 | }
9 |
10 | var result = 0;
11 | var sign;
12 | var i = 0
13 | var input = str
14 | while(input[i] === " "){ i++ };
15 |
16 | if(input[i] === "+") {
17 | sign = 1
18 | } else if(input[i] === "-") {
19 | sign = -1
20 | }
21 |
22 | if(sign) {
23 | i++
24 | }
25 |
26 | while(input[i] >= "0" && input[i] <= "9") {
27 | result = 10 * result + (input[i++] - "0")
28 | }
29 |
30 | result = sign ? sign * result : result
31 |
32 | if(result > 2147483647) {
33 | result = 2147483647
34 | } else if(result < -2147483648) {
35 | result = -2147483648
36 | }
37 |
38 | return result
39 | };
40 |
41 | console.log(myAtoi(" +0045a10"))
--------------------------------------------------------------------------------
/leetcode/fizzbuzz.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number} n
3 | * @return {string[]}
4 | */
5 | var fizzBuzz = function(n) {
6 | var result = []
7 | for(var i = 1; i<=n; i++) {
8 | var str = ""
9 | if(i % 3 == 0) {
10 | str += "Fizz"
11 | }
12 |
13 | if(i % 5 == 0) {
14 | str += "Buzz"
15 | }
16 | if(str === "") {
17 | str += i
18 | }
19 | result.push(str)
20 | }
21 |
22 | return result
23 | };
24 |
25 | console.log(fizzBuzz(15))
--------------------------------------------------------------------------------
/leetcode/hammingdistance.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number} x
3 | * @param {number} y
4 | * @return {number}
5 | */
6 | var hammingDistance = function(x, y) {
7 | var xor = x ^ y // number of different ones
8 | var d = 0
9 | while(xor) {
10 | if(xor & 0x01) {
11 | d++
12 | }
13 | xor >>= 1
14 | }
15 |
16 | return d
17 | };
18 |
19 |
20 | console.log(hammingDistance(1, 4))
--------------------------------------------------------------------------------
/leetcode/keyboardRow.js:
--------------------------------------------------------------------------------
1 | /**
2 | * problem: https://leetcode.com/problems/keyboard-row/#/description
3 | * @param {string[]} words
4 | * @return {string[]}
5 | */
6 | var findWords = function(words) {
7 | var result = [];
8 | var keyBoard = [
9 | new Set(["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"]),
10 | new Set(["A", "S", "D", "F", "G", "H", "J", "K", "L"]),
11 | new Set(["Z", "X", "C", "V", "B", "N", "M"])
12 | ];
13 | for(var i = 0; i< words.length; i++) {
14 | var row = -1;
15 | var oneRow = true;
16 | for(var c = 0; c < words[i].length; c++) {
17 | for(var r = 0; r< keyBoard.length; r++) {
18 | if(keyBoard[r].has(words[i].charAt(c).toUpperCase())) {
19 | if(row === -1) {
20 | row = r;
21 | } else {
22 | if(r !== row) {
23 | oneRow = false;
24 | }
25 | }
26 | break;
27 | }
28 | if(!oneRow) {
29 | break;
30 | }
31 | }
32 | if(!oneRow) {
33 | break;
34 | }
35 | }
36 |
37 | if(oneRow) {
38 | result.push(words[i])
39 | }
40 | }
41 |
42 | return result;
43 | };
44 |
45 |
46 | console.log(findWords(["Hello", "Alaska", "Dad", "Peace"]));
--------------------------------------------------------------------------------
/leetcode/longestAbsoluteFilePath.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string} input
3 | * @return {number}
4 | */
5 | var lengthLongestPath = function(input) {
6 | var stack = []
7 | var parts = input.split("\n")
8 | var longestPath = 0
9 | var currentLevel = 0
10 | for(var i = 0; i= 0) {
14 | // file
15 | } else { // dir
16 |
17 | }
18 | if(level >= currentLevel) {
19 | stack.push({ level: level, partName: pn })
20 | } else {
21 |
22 | }
23 | }
24 |
25 |
26 | function getPartLevel(p, startIndex) {
27 | if(p.length > startIndex && p[startIndex] != "\t") {
28 | return 0;
29 | }
30 |
31 | return 1 + getPartLevel(p, startIndex + 1)
32 | }
33 | };
--------------------------------------------------------------------------------
/leetcode/longestSubstringWithDistinctCharacters.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string} s
3 | * @return {number}
4 | */
5 | var lengthOfLongestSubstring = function(s) {
6 | var set = {}
7 | set[s[0]] = 1
8 | var longestSubstring = 0
9 | var longest = [s[0]]
10 | for(var i = 1; i= 0 && nums[i] >= nums[i + 1]) i--;
13 |
14 | if(i >= 0) {
15 | var j = nums.length - 1
16 | while(nums[j] <= nums[i]) j--
17 | swap(nums, i, j)
18 | }
19 |
20 | reverse(nums, i + 1, nums.length - 1)
21 | };
22 |
23 | function swap(nums, i, j) {
24 | var tmp = nums[i]
25 | nums[i] = nums[j]
26 | nums[j] = tmp
27 | }
28 |
29 | function reverse(nums, i, j) {
30 | while(i < j) {
31 | swap(nums, i++, j--)
32 | }
33 | }
34 | /*
35 | 1 2 3 -> 1 3 2
36 | 1 3 2 -> 2 1 3
37 | 2 1 3 -> 2 3 1
38 | 2 3 1 -> 3 1 2
39 | 3 1 2 -> 3 2 1
40 | 3 2 1 -> 1 2 3
41 | --------------
42 | 1 2 -> 2 1
43 | */
--------------------------------------------------------------------------------
/leetcode/numbercomplement.cs:
--------------------------------------------------------------------------------
1 | public class Solution {
2 | public static int FindComplement(int num) {
3 | return ~num + (highestOneBit(num) << 1);
4 | }
5 |
6 | private static int highestOneBit(int num) {
7 | if(num == 0) {
8 | return 0;
9 | }
10 |
11 | var result = 1;
12 | while((num >>= 1) > 0) result <<=1;
13 |
14 | return result;
15 | }
16 |
17 | public static void Main() {
18 | System.Console.WriteLine(FindComplement(5));
19 | }
20 | }
--------------------------------------------------------------------------------
/leetcode/numbersDisappearingFromArray.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number[]}
4 | */
5 | var findDisappearedNumbers = function(nums) {
6 | for(var i = 0; i 0) {
9 | nums[val] = -nums[val]
10 | }
11 | }
12 | var result = []
13 | for(i =0; i 0) {
15 | result.push(i + 1)
16 | }
17 | }
18 |
19 | return result
20 | };
21 |
22 | console.log(findDisappearedNumbers([4,3,2,7,8,2,3,1]))
--------------------------------------------------------------------------------
/leetcode/permutations.js:
--------------------------------------------------------------------------------
1 | function permute(nums) {
2 |
3 | var dict = {}
4 | for(var i = 0; i< nums.length; i++) {
5 | if(nums[i] in dict) {
6 | dict[nums[i]] ++
7 | } else {
8 | dict[nums[i]] = 1
9 | }
10 | }
11 |
12 | var result = []
13 |
14 | doPermute(nums, dict, 0, result)
15 | }
16 |
17 | function doPermute(nums, dict, level, result) {
18 | if(nums.length === level) {
19 | console.log(result)
20 | return
21 | }
22 | for(var n in dict) {
23 | if(dict[n] > 0) {
24 | result.push(n)
25 | dict[n] --
26 | doPermute(nums, dict, level + 1, result)
27 | result.pop()
28 | dict[n] ++
29 | }
30 | }
31 | }
32 |
33 | permute([1, 3, 2])
--------------------------------------------------------------------------------
/leetcode/removenthnode.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * function ListNode(val) {
4 | * this.val = val;
5 | * this.next = null;
6 | * }
7 | */
8 | /**
9 | * @param {ListNode} head
10 | * @param {number} n
11 | * @return {ListNode}
12 | */
13 | var removeNthFromEnd = function(head, n) {
14 | if(!head) {
15 | return head
16 | }
17 |
18 | var runner = head
19 | var fastRunner = head
20 | for(var i = 0; i 0 && nums[startIndex - 1] === nums[med]) {
19 | startIndex --
20 | }
21 | while(endIndex < nums.length - 1 && nums[endIndex + 1] === nums[med]) {
22 | endIndex ++
23 | }
24 |
25 | return [startIndex, endIndex]
26 | } else if (target < nums[med]) {
27 | end = med - 1
28 | } else {
29 | start = med + 1
30 | }
31 | }
32 |
33 | return [-1, -1]
34 | };
35 |
36 |
37 | console.log(searchRange([5, 7, 7, 8, 8, 10], 8))
--------------------------------------------------------------------------------
/leetcode/threesum.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number[][]}
4 | */
5 | var threeSum = function(nums) {
6 | var result = []
7 | nums.sort(function(a, b) {return a - b})
8 | for(var i = 0; i < nums.length - 2; i++) {
9 | if(i > 0 && nums[i] === nums[i - 1]) {
10 | continue
11 | }
12 | var sum = 0 - nums[i]
13 | var lo = i + 1
14 | var hi = nums.length - 1
15 | while(hi > lo) {
16 | if(nums[hi] + nums[lo] === sum) {
17 | result.push([nums[i], nums[lo], nums[hi]])
18 | lo ++
19 | hi --
20 | while(lo < hi && nums[lo] === nums[lo - 1]) lo ++
21 | while(hi > lo && nums[hi] === nums[hi + 1]) hi --
22 | } else if(nums[hi] + nums[lo] > sum) {
23 | hi --
24 | } else {
25 | lo ++
26 | }
27 | }
28 | }
29 | return result
30 | };
31 |
32 | console.log(threeSum([-1, 0, 1, 2, -1, -4]))
--------------------------------------------------------------------------------
/leetcode/threesumclosest.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @param {number} target
4 | * @return {number}
5 | */
6 | var threeSumClosest = function(nums, target) {
7 | if(!nums) {
8 | return 0
9 | }
10 | if(nums.length < 3) {
11 | return Math.sum(nums)
12 | }
13 | var minDelta = Number.MAX_VALUE
14 | var result = nums[0] + nums[1] + nums[2]
15 | nums.sort(function(a, b){return a - b})
16 | for(var i = 0; i Math.abs(target - sum)) {
26 | result = sum
27 | }
28 | if(sum > target){
29 | hi --
30 | } else {
31 | lo ++
32 | }
33 | }
34 | }
35 |
36 | return result
37 | };
38 |
39 | console.log(threeSumClosest([-1, 2, 1, -4], 1))
--------------------------------------------------------------------------------
/leetcode/twosums.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /**
4 | * @param {number[]} nums
5 | * @param {number} target
6 | * @return {number[]}
7 | */
8 | var twoSum = function(nums, target) {
9 | var dict = {}
10 |
11 | for(var i = 0; i
2 |
3 |
4 |
5 | PONG!
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/pong/scripts/ball.js:
--------------------------------------------------------------------------------
1 | function Ball() {
2 | this.r = 20
3 | this.vel = p5.Vector.random2D()
4 | this.pos = createVector(width / 2, height / 2)
5 | this.vel.mult(10)
6 | this.draw = function () {
7 | push()
8 | fill('WHITE')
9 | noStroke()
10 | ellipse(this.pos.x, this.pos.y, this.r, this.r)
11 | pop()
12 | }
13 |
14 | this.update = function (player1, player2) {
15 | this.pos.add(this.vel)
16 |
17 | if((this.pos.y >= height - this.r) || (this.pos.y <= this.r)) {
18 | this.hit("Y")
19 | }
20 |
21 | if(
22 | ((this.pos.x - this.r / 2) <= (player2.pos.x + player2.width / 2))
23 | &&
24 | (this.pos.y >= player2.pos.y - player2.height / 2) && (this.pos.y <= player2.pos.y + player2.height / 2)
25 | ) {
26 | this.hit("X", player2)
27 | }
28 |
29 | if(((this.pos.x - this.r / 2) >= (player1.pos.x - player1.width / 2))
30 | &&
31 | (this.pos.y >= player1.pos.y - player1.height / 2) && (this.pos.y <= player1.pos.y + player1.height / 2)
32 | ) {
33 | this.hit("X", player1)
34 | }
35 |
36 | if(this.pos.x >= width) {
37 | player1.score ++;
38 | this.reset()
39 | } else if (this.pos.x <= 0) {
40 | player2.score ++;
41 | this.reset()
42 | }
43 |
44 | }
45 |
46 | this.hit = function(axis, player) {
47 | if(axis === "Y") {
48 | this.vel.y *= -1
49 | } else if(axis === "X") {
50 | this.vel.x *= -1
51 | }
52 |
53 | if(player) {
54 | this.vel.add(player.vel)
55 | }
56 | }
57 |
58 | this.reset = function() {
59 | var sign = random() >= .5
60 | this.vel.x = (sign ? -1 : 1) * random(5, 10)
61 | this.vel.y = random(0, 0.75)
62 | this.pos.x = width / 2
63 | this.pos.y = height / 2
64 | }
65 | }
--------------------------------------------------------------------------------
/pong/scripts/board.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | function Board(pos) {
4 | this.pos = createVector(pos.x, pos.y)
5 | this.vel = createVector(0, 0)
6 | this.height = 200;
7 | this.width = 20;
8 | this.vel.mult(10)
9 | this.score = 0
10 |
11 | this.draw = function() {
12 | push()
13 | noStroke()
14 | fill("WHITE")
15 | translate(this.pos.x, this.pos.y)
16 | rect(0,- this.height / 2, this.width, this.height)
17 | pop()
18 | }
19 |
20 | this.update = function(dir) {
21 | this.pos.add(this.vel)
22 | this.limitY()
23 | }
24 |
25 | this.moveUp = function() {
26 | this.vel.y = -10
27 | }
28 |
29 | this.moveDown = function() {
30 | this.vel.y = 10
31 | }
32 |
33 | this.stopMoving = function() {
34 | this.vel.y = 0
35 | }
36 |
37 | this.limitY = function() {
38 | if(this.pos.y >= height - this.height / 2) {
39 | this.pos.y = height - this.height / 2
40 | }
41 |
42 | if(this.pos.y <= this.height / 2) {
43 | this.pos.y = this.height / 2
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/pong/scripts/sketch.js:
--------------------------------------------------------------------------------
1 | "use strict"
2 |
3 | var player1, player2, ball
4 |
5 | function setup() {
6 | var canvas = createCanvas(1080, 800)
7 |
8 | player1 = new Board(createVector(width - 40, height / 2))
9 | player2 = new Board(createVector(20, height / 2))
10 | ball = new Ball()
11 | }
12 |
13 |
14 | function draw() {
15 | push()
16 | background("BLACK")
17 | drawBackground()
18 | player1.draw()
19 | player2.draw()
20 | ball.draw()
21 | ball.update(player1, player2)
22 | player1.update()
23 | player2.update()
24 | displayScore()
25 | showFramerate()
26 | pop()
27 | }
28 |
29 | function keyPressed() {
30 | if(keyCode === DOWN_ARROW) {
31 | player1.moveDown();
32 | } else if (keyCode === UP_ARROW) {
33 | player1.moveUp();
34 | }
35 | else if(key === "W") {
36 | player2.moveUp();
37 | } else if(key === "S") {
38 | player2.moveDown();
39 | }
40 | }
41 |
42 | function keyReleased() {
43 | if(key === "W" || key === "S") {
44 | player2.stopMoving();
45 | } else if(keyCode === DOWN_ARROW || keyCode === UP_ARROW) {
46 | player1.stopMoving();
47 | }
48 | }
49 |
50 | function displayScore() {
51 | push()
52 | textAlign(CENTER)
53 | textSize(60)
54 | fill("WHITE")
55 | text(player1.score + " " + player2.score, width /2, 50)
56 | pop()
57 | }
58 |
59 | function showFramerate() {
60 | push()
61 | textAlign(LEFT)
62 | textSize(10)
63 | fill("WHITE")
64 | text(round(frameRate(), 0), width - 10, 10)
65 | pop()
66 | }
67 |
68 | function drawBackground() {
69 | push()
70 | stroke("WHITE")
71 | strokeWeight(5)
72 | for(var y = 0; y