/*
Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
寫一個(gè)程序輸出字符串?dāng)?shù)組表示從1到N的數(shù)字。
但是淹魄,當(dāng)數(shù)字為3的倍數(shù)時(shí)輸出字符串“Fizz”,當(dāng)數(shù)字為5的倍數(shù)時(shí)輸出字符串"Buzz",當(dāng)數(shù)字同為3及5的倍數(shù)時(shí)輸出“FizzBuzz”
*/
func fizzBuzz(number: Int) -> [String] {
var array = [String]()
for i in 1...number {
if i % 3 == 0 && i % 5 == 0{
array.append("FizzBuzz")
} else if i % 3 == 0 {
array.append("Fizz")
} else if i % 5 == 0 {
array.append("Buzz")
} else {
array.append("\(i)")
}
}
return array
}
let fizzBuzzArray = fizzBuzz(number: 15)
/*
Island Perimeter
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
*/
//每一塊陸地的周長與其上下左右有關(guān),上下左右無島則為4,其一方向有島則為3但校,依次推論蜗巧,則可得周長摩骨。
func getTheLandPerimeter(map:[[Int]]) -> Int{
//先判斷上下左右數(shù)組是否越界問題
//接著判斷每個(gè)1的上下左右是否存在另外的1
//根據(jù)1的數(shù)量確定其周長
//將所有周長整合
var perimeter = 0
for i in 0..<map.count {
let numberArr = map[i]
for j in 0..<numberArr.count{
let number = numberArr[j]
if number == 1 {
let up = i == 0 ? 0 : map[i - 1][j]
let down = i == (map.count - 1) ? 0 : map[i + 1][j]
let right = j == 0 ? 0 : map[i][j - 1]
let left = j == (numberArr.count - 1) ? 0 : map[i][j + 1]
let lands = up + right + left + down
perimeter+=(4 - lands)
}
}
}
return perimeter
}
let p = getTheLandPerimeter(map: [[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]])
print(p)
output:
["1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"]
16
Program ended with exit code: 0