Untitled
unknown
plain_text
2 years ago
1.5 kB
10
Indexable
Never
import kotlin.collections.* import java.util.* import java.util.concurrent.* const val NUMBER_OF_THREADS = 2 const val INPUT_SIZE = 10 const val INPUT_MIN = 0 const val INPUT_MAX = 10 @Volatile var result: Int = 0 fun main() { // INPUT val numbers = generateRandomInts() val chunks = splitInputToChunks(numbers.toIntArray()) // EXECUTOR val executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS) repeat(NUMBER_OF_THREADS) { i -> executor.execute { calculate(chunks[i]) } } executor.shutdown() executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS) // RESULT println("Result $result") } fun calculate(input: List<Int>) { // TODO: ADD YOUR OWN LOGIC HERE } fun generateRandomInts(): List<Int> { val random = Random() val range = IntRange(INPUT_MIN, INPUT_MAX) return List(INPUT_SIZE) { random.nextInt(range.last - range.first) + range.first } } fun splitInputToChunks(input: IntArray): List<List<Int>> { // Split array to subarrays val chunkSize = input.size / NUMBER_OF_THREADS val remainder = input.size % NUMBER_OF_THREADS val chunks = mutableListOf<List<Int>>() var i = 0 // Remain elements add to arrays equally for (j in 0 until NUMBER_OF_THREADS) { val size = chunkSize + if (j < remainder) 1 else 0 chunks.add(input.toCollection(ArrayList()).subList(i, i + size)) i += size } return chunks }