Basic Algorithm Scripting

An algorithm is a series of step-by-step instructions that describe how to do something.

To write an effective algorithm, it helps to break a problem down into smaller parts and think carefully about how to solve each part with code.

In this course, you’ll learn the fundamentals of algorithmic thinking by writing algorithms that do everything from converting temperatures to handling complex 2D arrays.

Convert Celsius to Fahrenheit

寫一個功能函數將攝氏的溫度轉換成華氏,華氏溫度=攝氏溫度乘以9/5+32
function convertToF(celsius) {
  let fahrenheit = 9/5 * celsius + 32;
  return fahrenheit + “°F”;
}
convertToF(30);
console.log(convertToF(30));

得到結果是

86°F

Reverse a String

翻轉一個字串的順序A-Z變成Z-A

方法1

方法2

function reverseString(str) {
    return str
      .split(“”)
      .reverse()
      .join(“”); //如果沒有做這行的話會變成[ ‘o’, ‘l’, ‘l’, ‘e’, ‘h’ ]
}
reverseString(“hello”);
console.log(reverseString(“hello”));

 

Factorialize a Number

計算階層5!
方法1:For迴圈
function factorialize(num) {
  let product = 1;
  for (let i = 2; i <= num; i++) {
    product = product * i;
  }
  return product;
}
factorialize(5);
1*2 = 2
1*2*3 = 6
1*2*3*4 = 24
1*2*3*4*5 = 120

 

方法2:運用遞迴

function factorialize(num) {
  if (num === 0) {
    return 1;
  }
  return num * factorialize(num – 1);
}
factorialize(5);

方法3:運用遞迴

function factorialize(num, factorial = 1) {
  if (num === 0) {
    return factorial;
  } else {
    return factorialize(num – 1, factorial * num);
  }
}
factorialize(5);
方法4:ES6寫法+運用fill功能和reduce功能
function factorialize(num) {
  return num < 0 ? 1 :
    new Array(num)
      .fill(undefined)
      .reduce((product, _, index) => product * (index + 1), 1);
}
factorialize(5);

Reference answer


 

Find the Longest Word in a String

找出字串中最長的單字

方法1:空白鍵切割,for迴圈

function findLongestWordLength(str) {
  let words = str.split(‘ ‘);
  console.log(words);
  let maxLength = 0;
  for (let i = 0; i < words.length; i++){
    if (words[i].length > maxLength){
      maxLength = words[i].length;
    }
  }
  return maxLength;
}
findLongestWordLength(“The quick brown fox jumped over the lazy dog”);
console.log(findLongestWordLength(“The quick brown fox jumped over the lazy dog”));
設定words是由空白鍵分割成的字串

方法2: 使用reduce函數的功能

方法3:

方法4:


Return Largest Numbers in Arrays

 

 

方法1:使用For迴圈兩次

 

方法2:使用reduce功能

function largestOfFour(arr) {
  return arr.map(function(group) {
    return group.reduce(function(prev, current) {
      return current > prev ? current : prev;
    });
  });
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

方法3:使用Math.max()

方法4:

Confirm the Ending

 

方法1:

function confirmEnding(str, target) {
  if (str.slice(str.length – target.length) === target){
    return true;
  } else{
    return false;
  }
}
confirmEnding(“Bastian”, “n”);

 


Repeat a String Repeat a String

 

重複字串

方法1:

function repeatStringNumTimes(str, num) {
  if (num < 1) {
    return “”;
  } else {
    return str + repeatStringNumTimes(str, num -1);
  }
}
repeatStringNumTimes(“abc”, 3);
console.log(repeatStringNumTimes(“abc”, 3));

Truncate a String

 

function truncateString(str, num) {
  if (str.length > num){
    return str.slice(0, num) + “…”;
  } else {
    return str;
  }
}
truncateString(“A-tisket a-tasket A green and yellow basket”, 8);
console.log(truncateString(“A-tisket a-tasket A green and yellow basket”, 8))
得到結果
A-tisket…

 


Finders Keepers

尋找字串中有沒有奇數,顯示第一個出現的

方法1

function findElement(arr, func) {
  let num = 0;
  for (let i = 0; i < arr.length; i++) {
    num = arr[i];
    if (func(num)) {
      return num;
    }
  }
}
findElement([1, 2, 3, 4], num => num % 2 === 0);
console.log(findElement([1, 2, 3, 4], num => num % 2 === 0));

得到結果是2

 


Boo who

檢查是不是屬於布林值,是的話給true,不是的話給false

 

function booWho(bool) {
  return typeof bool === “boolean”;
}
booWho(null);

 


Title Case a Sentence

字串的第一個字母變成英文大寫

function titleCase(str) {
  const newTitle = str.split(” “);
  const updatedTitle = [];
  for (let st in newTitle) {
    updatedTitle[st] = newTitle[st][0].toUpperCase() + newTitle[st].slice(1).toLowerCase();
  }
  return updatedTitle.join(” “);
}
titleCase(“I’m a little tea pot”);

 


Slice and Splice

分割和重新排序字串

function frankenSplice(arr1, arr2, n) {
  // It’s alive. It’s alive!
  let localArray = arr2.slice();
  for (let i = 0; i < arr1.length; i++) {
    localArray.splice(n, 0, arr1[i]);
    n++;
  }
  return localArray;
}
frankenSplice([1, 2, 3], [4, 5, 6], 1);
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));

Falsy Bouncer

 

移除falsenull0""undefined, and NaN.的值

方法1:如果array的項目數值是true,就加入字串

function bouncer(arr) {
  let newArray = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i]) newArray.push(arr[i]);
  }
  return newArray;
}
bouncer([7, “ate”, “”, false, 9]);
console.log(bouncer([7, “ate”, “”, false, 9]));
得到結果
[ 7, 'ate', 9 ]

方法2:利用filter功能函數

function bouncer(arr) {
  return arr.filter(Boolean);
}
bouncer([7, “ate”, “”, false, 9]);
console.log(bouncer([7, “ate”, “”, false, 9]));

Where do I Belong

找出字串中大於設定數值的數字

方法1:使用filter篩選條件,再把數字的多寡定出來。

function getIndexToIns(arr, num) {
  return arr.filter(val => num > val).length;
}
getIndexToIns([40, 60], 50);

Mutations

找出是否具有完全相同的字母

function mutation(arr) {
  let test = arr[1].toLowerCase();
  let target = arr[0].toLowerCase();
  for (let i = 0; i < test.length; i++) {
    if (target.indexOf(test[i]) < 0) return false;
  }
  return true;
}
mutation([“hello”, “hey”]);

Chunky Monkey

將字串分成不同份數

方法1:for 迴圈,設定暫時結果的字串與預期結果的字串

function chunkArrayInGroups(arr, size) {
  let temp = [];
  let result = [];
  for (let a = 0; a < arr.length; a++) {
    if (a % size !== size – 1) temp.push(arr[a]);
    else {
      temp.push(arr[a]);
      result.push(temp);
      temp = [];
    }
  }
  if (temp.length !== 0) result.push(temp);
  return result;
}
chunkArrayInGroups([“a”, “b”, “c”, “d”], 2);
console.log(chunkArrayInGroups([“a”, “b”, “c”, “d”], 2));
得到結果為:
[ [ ‘a’, ‘b’ ], [ ‘c’, ‘d’ ] ]

 

最後修改日期: 2022 年 6 月 16 日

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。