С Новым годом! Форум программистов, компьютерный форум, киберфорум
Java
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/21: Рейтинг темы: голосов - 21, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 12.11.2019
Сообщений: 5

Перевести код с Kotlin на Java

28.09.2020, 22:25. Показов 4292. Ответов 1

Студворк — интернет-сервис помощи студентам
Kotlin
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const val EMPLOYED_BEES_COUNT: Int = 2
const val ONLOOKER_BEES_COUNT: Int = 28
const val PALETTE_SIZE: Int = 10000
 
class ABCAlgorithm(private val initialGraph: Graph) {
    var graph = Graph(initialGraph.getAdjMatrix())
    private var availableVertices: Array<Int> = graph.getVertexArray()
    private val palette: Array<Int> = Array(PALETTE_SIZE) { i -> i }
    private var usedColors: MutableList<Int> = mutableListOf()
 
    fun calculateChromaticNumber(): Int {
        while (!this.isFinished()) {
            val selectedVertices = this.sendEmployedBees()
            this.sendOnlookerBees(selectedVertices)
        }
        val chromaticNumber = usedColors.size
        return chromaticNumber
    }
 
    fun resetAlgorithm() {
        usedColors = mutableListOf()
        availableVertices = graph.getVertexArray()
        graph = Graph(initialGraph.getAdjMatrix())
    }
 
    private fun isFinished(): Boolean {
        return graph.isAllVerticesValidColored()
    }
 
    private fun sendEmployedBees(): Array<Int> {
        val selectedVertices: MutableList<Int> = MutableList(0) { i -> i }
        for (employedBee in 0 until EMPLOYED_BEES_COUNT) {
            val randomSelectedVertexIndex = (0 until availableVertices.size).random()
            val randomSelectedVertex = availableVertices[randomSelectedVertexIndex]
            availableVertices = availableVertices
                .filter { vertex -> vertex != randomSelectedVertex }
                .toTypedArray()
            selectedVertices += randomSelectedVertex
        }
        return selectedVertices.toTypedArray()
    }
 
    private fun sendOnlookerBees(selectedVertices: Array<Int>) {
        val selectedVerticesDegrees = selectedVertices.map { vertex ->
            graph.getVertexDegree(vertex)
        }.toTypedArray()
        val onlookerBeesSplit = this.getOnlookerBeesSplit(selectedVerticesDegrees)
        selectedVertices.forEachIndexed { selectedVertexIndex, selectedVertex ->
            val onlookerBeesCountForVertex = onlookerBeesSplit[selectedVertexIndex]
            val connectedVertices = graph.getConnectedVertexes(selectedVertex)
            this.colorConnectedVertices(connectedVertices, onlookerBeesCountForVertex)
            this.colorVertex(selectedVertex)
        }
    }
 
    private fun getOnlookerBeesSplit(selectedVerticesDegrees: Array<Int>): Array<Int> {
        val nectarValues = this.getNectarValues(selectedVerticesDegrees)
        var onlookerBeesCount = ONLOOKER_BEES_COUNT
        return nectarValues.mapIndexed { index, nectar ->
            if (index == nectarValues.size) onlookerBeesCount
            else {
                val onlookerBeesCountForCurrentVertex = (onlookerBeesCount * nectar).toInt()
                onlookerBeesCount -= onlookerBeesCountForCurrentVertex
                onlookerBeesCountForCurrentVertex
            }
        }.toTypedArray()
    }
 
    private fun getNectarValues(selectedVerticesDegrees: Array<Int>): Array<Double> {
        val summarySelectedVerticesDegree = selectedVerticesDegrees.sum()
        return selectedVerticesDegrees.map { vertexDegree ->
            (vertexDegree / summarySelectedVerticesDegree).toDouble()
        }.toTypedArray()
    }
 
    private fun colorConnectedVertices(connectedVertices: Array<Int>, onlookerBeesCount: Int) {
        connectedVertices.forEachIndexed { connectedVertexIndex, connectedVertex ->
            if (connectedVertexIndex >= onlookerBeesCount - 1) return
            colorVertex(connectedVertex)
        }
    }
 
    private fun colorVertex(vertex: Int) {
        val availableColors = usedColors.toList().toMutableList() //copy array
        var isColoredSuccessfully = false
        while (!isColoredSuccessfully) {
            if (availableColors.size == 0) {
                val newColor = getNextColor()
                usedColors.plusAssign(newColor)
                graph.tryToColorAndCheckIsValid(vertex, newColor)
                isColoredSuccessfully = true
                break
            }
            val randomAvailableColorIndex = (0 until availableColors.size).random()
            val color = availableColors[randomAvailableColorIndex]
            availableColors.removeAt(randomAvailableColorIndex)
            isColoredSuccessfully = graph.tryToColorAndCheckIsValid(vertex, color)
        }
    }
 
    private fun getNextColor(): Int {
        return palette[usedColors.size]
    }
 
     val ITERATIONS_COUNT: Int = 1000
     val ITERATIONS_PER_STEP: Int = 20
    fun test() {
        var bestResult = calculateChromaticNumber()
        resetAlgorithm()
        for (iteration in 0..ITERATIONS_COUNT) {
            if (iteration % ITERATIONS_PER_STEP == 0) {
                println("on iteration $iteration best result is $bestResult")
            }
            val newChromaticNumber = calculateChromaticNumber()
            if (newChromaticNumber < bestResult) {
                bestResult = newChromaticNumber
               graph.printColors()
            }
            resetAlgorithm()
        }
    }
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
28.09.2020, 22:25
Ответы с готовыми решениями:

Перевести код с Kotlin на С++
import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt fun main() { val (x,n,e) = readLine()!!.split(&quot;...

Переписать код kotlin на java
Нашел библиотеку для выбора цвета: https://github.com/side-codes/andColorPicker но в примерах используется kotlin (я пишу на java). ...

Kotlin "it" как перевести на java?
есть пример кода на котлине: override fun one(id: Long): Observable&lt;Banner&gt; { return bannerDataStoreFactory ...

1
 Аватар для Aviz__
2736 / 2046 / 506
Регистрация: 17.02.2014
Сообщений: 9,462
29.09.2020, 07:31
Borovyk, какую задачу решает код?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
29.09.2020, 07:31
Помогаю со студенческими работами здесь

Как перевести код с паскаля на Java. Пытался сам но код не хочет работать переведенный
А сам код на паскале работает. Вот код на паскале var i,j,m,c,d: integer; A:array of integer; begin c:=1; ...

Перевести с С++ на Kotlin
#include &lt;iostream&gt; void printNumbers(int n) { if (n &lt;= 0) return; printNumbers(n - 1); std::cout &lt;&lt; ' ' &lt;&lt; n; } ...

Перевести код с С++ в Java
Добрый день. Нужна помощь перевода кода С++ в Java код. #include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main()...

Перевести код с С++ на Java
код:#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;cmath&gt; #include &lt;cstdlib&gt; using namespace std; double f(double x) { ...

Перевести код java на с++
Код на Java: package com.company; import java.lang.String; import java.util.Scanner; class Main { public...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru