D30_ 第三週作業寫完


Posted by Christy on 2021-05-18

LIOJ 1004 聯誼順序比大小

  • 解題想法:想了半天寫了下面的版本,還是不對,所以我決定模仿學習,強迫輸入。
function solve(lines) {
    let n = Number(lines[0])
    for(let i=1; i<=n; i++) {
        console.log(compare(lines[i][0], lines[i][1], lines[i][2]))
    }
}

function compare(n1, n2, p) {
    if(n1 === n2) {
        return 'DRAW'
    }

    if(n1 > n2 && p === 1) {
        return 'A'
    } else if (n1 > n2 && p === -1) {
        return 'B'
    }
}
  • 我是正解
function compare(a, b, p) {
  if (a === b) return "DRAW"

  // 先假設我們都是比大,所以 A 大就回傳 A,B 大就回傳 B
  // 那如果是比小怎麼辦?把 AB 對調就好
  // 假設 A 是 5,B 是 3,我們的邏輯會回傳 A
  // 但如果是比小,把 AB 對調,就會回傳 B 了
  // 這段一開始最難理解,如果 p == -1,那才會跑進這裡
  if (p == -1) {
  // 下面在說的是把 A B 順序對調
    let temp = a
    a = b
    b = temp
  }

  const lengthA = a.length
  const lengthB = b.length
  // 如果長度比較長的,當然比較大
  if (lengthA != lengthB) {
      return lengthA > lengthB ? "A" : "B"
  }
  // 這裡是在比較數字的順序大小
  for (let j = 0; j < lengthA; j++) {
      if (a[j] == b[j]) {
          continue;
      }
      return a[j] > b[j] ? "A" : "B"
  }
}

function solve(lines) {
  let m = Number(lines[0])
  for(let i=1;i<=m; i++){
    let [a, b, p] = lines[i].split(' ')
    console.log(compare(a, b, p))
  }
}

新發現:字串其實比的是字典序,如果兩個字串長度相同,那字典序其實就是數字大小的順序

  • 字串在比較的時候,就自動比較字典序大小了,所以不用特地比較字串的每一個位數的大小。
//OJ 輸入
var readline = require('readline');

var lines = []
var rl = readline.createInterface({
  input: process.stdin
});

rl.on('line', function (line) {
  lines.push(line)
});

rl.on('close', function() {
  solve(lines)
})

function solve(lines) {
    let n = Number(lines[0])

    for(let i=1; i<=n; i++) {
        let temp = lines[i].split(' ')
        let a = temp[0]
        let b = temp[1]
        let p = temp[2]
        console.log(compare(a, b, p))
    }
}

function compare(a, b, p) {
  if (a === b) return "DRAW"

  if (p == -1) {
    let temp = a
    a = b
    b = temp
  }

  const lengthA = a.length
  const lengthB = b.length

  if (lengthA != lengthB) {
      return lengthA > lengthB ? "A" : "B"
  }
  return a > b ? 'A' : 'B'
}
  • 今天每一題都拿到 AC 了,跟 eslint 奮戰三個小時被通過了,但 LIOJ 出現 wrong answer...想哭 😭









Related Posts

Print lots of stars patterns

Print lots of stars patterns

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode

Ubuntu 對調左側 ctrl 鍵與大寫鍵的 keycode

一起探討 Micro Frontends 的世界

一起探討 Micro Frontends 的世界


Comments