iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 5
0
自我挑戰組

菜鳥工程師的奇幻漂流:跟著kata活化手指和意識系列 第 5

Find the smallest integer in the array

今日kata

原始題目如下:(8kyu)
Given an array of integers your solution should find the smallest integer.
For example:
Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty.

翻譯:
回傳陣列中最小的整數

範例:
[34, 15, 88, 2] 會得到 2
[34, -345, -1, 100] 會得到 -345


構想&解法

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return args.sort((a,b)=>a-b)[0]
  }
}

使用sort()對陣列中的元素進行排序,依數值由小到大排列,回傳第一個元素。
註:sort()預設是根據Unicode編碼位置。

其他解法觀摩

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min(...args)
  }
}

內建的Math物件,將陣列展開並傳入Math.min()中,取得最小數值。


整理用法

陣列.sort()

語法:arr.sort([compareFunction]),直接改變arr原陣列。

範例:

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// [1, 100000, 21, 30, 4]

其中如果沒有給compareFunction,預設會以Unicode編碼進行排列,Ex:100會在2前。

可以使用compareFunction來自訂排序,compareFunction(a,b)接受兩個參數,回傳一個數字:

  • compareFunction(a,b)小於0,a會排在b之前
  • compareFunction(a,b)等於0,a,b順序不動(各家瀏覽器可能有差異)
  • compareFunction(a,b)大於0,a會排在b之後

過程如下:

const numbers=[2,9,100,5];
const sortedNumbers=numbers.sort((a,b)=>{
  console.log(a,b) // 觀察每次傳入的a,b為何
  if(a<b){
    return -1
  }else if(a>b){
    return 1
  }else {
    return 0
  }
})
// 瀏覽器不同 傳入的a,b會有差異,但不影響排序
// [In Chrome]
// 9 2
// 100 9
// 5 100
// 5 9
// 5 2
// sortedNumbers=[2,5,9,100]

資料會兩兩一組進行比較,根據比較結果決定要不要置換。
比對概念如下:
https://ithelp.ithome.com.tw/upload/images/20200916/20128122FIfkXAtugs.jpg
圖摘自:w3resource.com

[In Chrome]

  1. (a=9、b=2)
    9 > 2 Return值大於0,b要放前面 (2放9之前),陣列無異動[2,9,100,5]
  2. (a=100、b=9)
    100 > 9 Return值大於0,b要放前面 (9要放100前),陣列無異動[2,9,100,5]
  3. (a=5、b=100)
    5 < 100 Return值小於0,a要放前面 (5要和100置換),陣列異動為[2,9,5,100]
  4. (a=5、b=9)
    5 < 9 Return值小於0,a要放前面 (5要和9置換),陣列異動為[2,5,9,100]
  5. (a=5、b=2)
    5 > 2 Return值大於0,b要放前面 (2放5之前),陣列無異動[2,9,5,100]

簡化版:

// 由小往大 升冪排列
arr.sort((a,b)=>a-b);
// 由大至小 降冪排列
arr.sort((a,b)=>b-a);

推薦閱讀:
[JavaScript] 從 Array 的 sort 方法,聊到各瀏覽器的實作,沒想到 Chrome 和FireFox 的排序如此不同


Math物件

屬於內建的物件,常用方法如下:

  • Math.abs(x)
    • 取得x絕對值
  • Math.ceil(x)
    • 取得大於x的最小整數 (找天花板/沿著數線往右邊找值)
    • Math.ceil(7.3)=8
  • Math.floor(x)
    • 取得小於x的最大整數 (找地板/沿著數線往左邊找值)
    • Math.floor(7.3)=7
  • Math.max([value1[, value2[, ...]]])
    • 回傳最大的數字
    • Math.max(1,2,3,4,5)=5
  • Math.min([value1[, value2[, ...]]])
    • 回傳最小的數字
    • Math.min(1,2,3,4,5)=1
  • Math.pow(x,y)
    • 回傳x的y次方
    • Math.pow(2,3)=8
  • Math.random()
    • 回傳0~1之間隨機數(包含0,不包含1)
    • 0~0.999999999
    • Ex: Math.floor(Math.random() * 10) 可以得到0~9隨機整數
  • Math.round(x)
    • x四捨五入
    • Math.round(21.2)=21

以上為今日分享的內容,若有錯誤或是建議,請再隨時和我聯繫。


上一篇
Smallest unused ID
下一篇
Find the odd int
系列文
菜鳥工程師的奇幻漂流:跟著kata活化手指和意識30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言