Created
June 5, 2022 15:11
-
-
Save ayaysir/211c9016754d62ee544a6345ea9f21d2 to your computer and use it in GitHub Desktop.
makeShuffledArray
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Array+.swift | |
// MusicScale | |
// | |
// Created by yoonbumtae on 2022/06/05. | |
// | |
import Foundation | |
enum ShuffleArrayError: Error { | |
case totalCountIsGreaterThanArrayCount, newArrayCountAndTotalCountNotSame | |
} | |
extension Array { | |
func makeShuffledArray(totalCount: Int) throws -> Self { | |
guard self.count < totalCount else { | |
throw ShuffleArrayError.totalCountIsGreaterThanArrayCount | |
} | |
var newArray = self | |
let repeatCount = (totalCount / self.count - 1) | |
if repeatCount >= 1 { | |
for _ in 0..<repeatCount { | |
let shuffledArray = self.shuffled() | |
newArray += shuffledArray | |
} | |
} | |
// 남은 개수 이어붙이기 | |
let remainCount = totalCount - newArray.count | |
newArray += Array(self[0..<remainCount]) | |
guard newArray.count == totalCount else { | |
throw ShuffleArrayError.newArrayCountAndTotalCountNotSame | |
} | |
return newArray | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment