程式設計概念 - 演算法

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡

An algorithm uses a series of steps to determine an outcome. Steps can be a set of directions, comparisons, or even a mathematical formula.

Your daily life is full of algorithms that you use without thinking about it. They help you make decisions, create things, and solve problems.

實際生活範例:

  • Checking if you have enough money to buy a snack.
  • Getting dressed in the morning.
  • Drawing stick figures.

程式範例:

  • Checking if a skill level is high enough to use an item.
  • Sorting a list of items into alphabetical order.
  • A player standing on lava loses 5 health every second. If they reach 0, they respawn.

在程式中建立演算法

In real life, we don't usually think about the algorithms we use everyday. Computers however, need algorithms to be coded step-by-step and use at least one of three methods to solve a problem or produce an outcome.

方法範例
選擇 - 使用條件語句如 if/then 來確定輸出。

if time == 0 then
stopLightColor = red
end

排序 - 一組精確的步驟。


local function createBridge()
create new block
size block
set color
rotate
set location
parent to workspace
end

迭代 - 根據需要重複部分程式碼,如在 for 迴圈或乘法中。


for countDown = 10, 1, -1 do
time -= 1
task.wait(1)
end

組合演算法

Much like larger problems can be broken into smaller problems, some algorithms can be broken down into a series of smaller algorithms.

Think of your real-life morning time algorithm to get dressed. If that's your main algorithm, it might use one algorithm for picking out your clothes, and a second algorithm for putting clothes on.

穿衣服的偽代碼

-- 第一個演算法用來挑選衣服
local function pickClothes()
pick top clothing
pick bottom clothing
pick Socks
pick Shoes
end
-- 第二個演算法用來穿衣服
local function putOnClothes()
put on top clothing
put on bottom clothing
put on socks
put on shoes
end
-- 主演算法,呼叫 pickClothes() 和 putOnClothes()
local function getDressed()
pickClothes()
putOnClothes()
end

總結

演算法是提供結果的預定義步驟。在日常生活中,演算法解決像是穿衣服、上班或做蛋糕等問題。在程式中,演算法解決像是管理網站、處理交通擁堵或運行遊戲機制等問題。為了完成目標,演算法經常會呼叫其他演算法。

演算法使用三種不同的方法來得出結論;選擇迭代排序。選擇使用條件語句,例如 if/then 語句。迭代根據需要重複部分程式碼。排序則使用一系列步驟來產生結果。

©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。