Don't LeetCode Yet - 4 - Let's Code
From Pseudocode to Actual code
Function filling
Write down the action inside the main structure first!
Example LIOJ problem 1020
Li’s solution:
if( X is Prime){} |
to
if(isPrime(X)){ |
Divide problem into small pieces: Find Prime numbers in an array = List the array + check if it is prime
Nested loop
Simplify the problem
Solve the simplified problem first.
Example LIOJ problem 1021
print a star pyramid:
* |
If we don’t know how to print multiple stars in one line, print out 1 star for each line first.
for (let i=1;i<=N; i++){ |
Don’t really need .repeat()
method
Programing San-Bao
Iteration ,Function, Condition
Try not to solve problem with built-in function/method but the San-Bao (like the .repeat()
method above.)
Example
LIOJ problem 1022 print the star pyramid
- First write down the basic structure:
function solve(lines){
for (let i=1; i<=lines[0]; i++){
printStars(i)
}
}
function printStars(n){
} - then fill in the
printStars()
function. When trying to write the detail of this function, I figured out that we need to pass two arguments inside. It means that I NEED TO FIND THE LOGIC before solving the problem.
Logic from the instructor:
- Need to print out N lines
- The line i will have 2i-1 stars
- stars need to be centered
- need N-i white space in front of each line
My solution logic:
- Print out N lines
- Print out the space in front, so the i will start from N and decreasing
- Each line will have i-1 spaces
- add the stars after the spaces: 1 initial star for each line + 2(N-i) stars for each line
The instructor used a support function to do the repetition
function repeat(str, n){ |
Multiplication table
Practice nested loop
Find Square numbers
My solution:
var divisor = lines[0] |
Instructor’s solution:
Math.sqrt()
orMath.floor()
- Loop through all square numbers under 100
while(i*i <=100){
console.log(i*i)
i++
}
Project 4
Print a tree
Like printing a pyramid, just add the trunk.
And maybe make it prettier:
function solve(lines) { |
N M multiplication table
Find Narcissistic numbers
NumI = NumI[0]^NumI.length + …… + NumI[NumI.length]^NumI.length
- Loop through Number I - j
- check if it returns true
I put the numbers into array to get each digit.
Didn’t pay attention to the input so got several “Wrong Answer” submitions.