Skip to content

Instantly share code, notes, and snippets.

@ayaysir
Created June 5, 2022 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayaysir/211c9016754d62ee544a6345ea9f21d2 to your computer and use it in GitHub Desktop.
Save ayaysir/211c9016754d62ee544a6345ea9f21d2 to your computer and use it in GitHub Desktop.
makeShuffledArray
//
// 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