path stringlengths 5 169 | owner stringlengths 2 34 | repo_id int64 1.49M 755M | is_fork bool 2
classes | languages_distribution stringlengths 16 1.68k ⌀ | content stringlengths 446 72k | issues float64 0 1.84k | main_language stringclasses 37
values | forks int64 0 5.77k | stars int64 0 46.8k | commit_sha stringlengths 40 40 | size int64 446 72.6k | name stringlengths 2 64 | license stringclasses 15
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
query-tree/src/main/kotlin/name/djsweet/query/tree/IntervalTree.kt | djsweet | 719,705,276 | false | {"Kotlin": 724408, "Java": 3144} | // SPDX-FileCopyrightText: 2023 <NAME> <<EMAIL>>
//
// SPDX-License-Identifier: MIT
package name.djsweet.query.tree
import kotlin.NoSuchElementException
internal fun <T : Comparable<T>>compareRanges(leftLeft: T, leftRight: T, rightLeft: T, rightRight: T): Int {
val leftCompare = leftLeft.compareTo(rightLeft)
if (leftCompare != 0) {
return leftCompare
}
return leftRight.compareTo(rightRight)
}
// Our ranges are closed on both ends, so first == second is perfectly acceptable.
internal fun <T: Comparable<T>>enforceRangeInvariants(range: Pair<T, T>): Pair<T, T> {
val rangeCompare = range.first.compareTo(range.second)
return if (rangeCompare > 0) {
Pair(range.second, range.first)
} else {
range
}
}
internal fun <T: Comparable<T>>rangeOverlaps(leftLow: T, leftHigh: T, rightLow: T, rightHigh: T): Boolean {
val rangeLowNodeLow = leftLow.compareTo(rightLow)
val rangeLowNodeHigh = leftLow.compareTo(rightHigh)
val rangeHighNodeLow = leftHigh.compareTo(rightLow)
val rangeHighNodeHigh = leftHigh.compareTo(rightHigh)
// This low between other range
var overlaps = rangeLowNodeLow >= 0 && rangeLowNodeHigh <= 0
// This high between other range
overlaps = overlaps || (rangeHighNodeLow >= 0 && rangeHighNodeHigh <= 0)
// Other range low between this
overlaps = overlaps || (rangeLowNodeLow <= 0 && rangeHighNodeLow >= 0)
// Other range high between this
overlaps = overlaps || (rangeHighNodeLow <= 0 && rangeHighNodeHigh >= 0)
return overlaps
}
/**
* Represents an ordered pair of two values, interpreted as a closed-interval range.
*
* This type is used extensively inside an [IntervalTree] to encode keys.
*/
data class IntervalRange<T: Comparable<T>> internal constructor(
/**
* One of the two values in an [IntervalRange], either equal to or less than [upperBound].
*/
val lowerBound: T,
/**
* One of the two values in an [IntervalRange], either equal to or greater than [lowerBound].
*/
val upperBound: T
): Comparable<IntervalRange<T>> {
companion object {
/**
* Creates an [IntervalRange] from a [Pair].
*
* The values of the pair are automatically reordered in the resulting
* IntervalRange such that [lowerBound] is always less than or equal to
* [upperBound], which is to say that if [Pair.first] is greater than
* [Pair.second], `lowerBound` will be set to `Pair.second` and `upperBound`
* will be set to `Pair.first`.
*/
fun <T: Comparable<T>> fromPair(p: Pair<T, T>): IntervalRange<T> {
val (lowerBound, upperBound) = enforceRangeInvariants(p)
return IntervalRange(lowerBound, upperBound)
}
/**
* Creates an [IntervalRange] given potential bounds.
*
* The values of the given bounds are automatically reordered in the resulting
* IntervalRange such that [lowerBound] is always less than or equal to
* [upperBound], which is to say that if [maybeLower] is greater than [maybeUpper],
* `lowerBound` will be set to `maybeUpper` and `upperBound` will be set to
* `maybeLower`.
*/
fun <T: Comparable<T>> fromBounds(maybeLower: T, maybeUpper: T): IntervalRange<T> {
val rangeCompare = maybeLower.compareTo(maybeUpper)
return if (rangeCompare > 0) {
IntervalRange(maybeUpper, maybeLower)
} else {
IntervalRange(maybeLower, maybeUpper)
}
}
}
/**
* Converts this [IntervalRange] to a [Pair].
*
* [Pair.first] is set to [lowerBound] and [Pair.second] is set to [upperBound].
*/
fun toPair(): Pair<T, T> {
return Pair(this.lowerBound, this.upperBound)
}
/**
* Checks whether this [IntervalRange] overlaps with the [other] IntervalRange.
*
* Overlapping is closed-interval, meaning that
* - If both bounds of this interval range are between or equal to either bound
* of the other IntervalRange, the ranges overlap.
* - If both bounds of the other interval range are between or equal to either bound
* of this IntervalRange, the ranges overlap.
* - If either bound of this IntervalRange is between or equal to either bound
* of the other IntervalRange, the ranges overlap.
*
* If none of these conditions hold, the ranges do not overlap.
*/
fun overlaps(other: IntervalRange<T>): Boolean {
return rangeOverlaps(this.lowerBound, this.upperBound, other.lowerBound, other.upperBound)
}
override fun compareTo(other: IntervalRange<T>): Int {
return compareRanges(this.lowerBound, this.upperBound, other.lowerBound, other.upperBound)
}
}
/**
* Represents a key/value pair held by an [IntervalTree].
*/
data class IntervalTreeKeyValue<T: Comparable<T>, V> internal constructor(val key: IntervalRange<T>, val value: V)
/**
* Represents a key/value pair held by an [IntervalTree], with an additional [balance] member.
*
* The semantics of [key] and [value] in this type are identical to those of [IntervalTreeKeyValue]. The [balance]
* member indicates the relative "weight" of the node corresponding to this key/value pair in the IntervalTree.
* A balance of 0 indicates that both the left and right children of the corresponding node have the same weight,
* a balance less than 0 indicates that the left child of the corresponding node has a greater weight than the
* right child, and a balance greater than 0 indicates that the right child of the corresponding node has a balance
* greater than the left child.
*
* Consumers typically will not need to consider the `balance` during normal operation. It is exposed for testing
* purposes, to verify that no node in the tree ever has a balance with an absolute value greater than 1, but can
* otherwise be safely ignored.
*/
data class IntervalTreeKeyValueWithNodeBalance<T: Comparable<T>, V> internal constructor(
val key: IntervalRange<T>,
val value: V,
val balance: Int
)
/*
* IntervalTree is an AVL tree, augmented according to the description of an augmented Red-Black Tree in
* Introduction to Algorithms (3rd Ed.) (2009)
* <NAME> Leiserson, <NAME> Rivest, <NAME> <NAME>
*/
internal class TreeNode<T : Comparable<T>, V>(
val leftKey: T,
val rightKey: T,
val maxRightKey: T,
val value: IntervalTreeKeyValue<T, V>,
val leftNode: TreeNode<T, V>?,
val rightNode: TreeNode<T, V>?,
val height: Byte
) {
companion object {
fun <T : Comparable<T>, V>newInstance(
keys: IntervalRange<T>,
value: V,
leftNode: TreeNode<T, V>?,
rightNode: TreeNode<T, V>?
): TreeNode<T, V> {
val (leftKey, rightKey) = keys
return newInstance(leftKey, rightKey, value, leftNode, rightNode)
}
fun <T: Comparable<T>, V>newInstance(
leftKey: T,
rightKey: T,
value: IntervalTreeKeyValue<T, V>,
leftNode: TreeNode<T, V>?,
rightNode: TreeNode<T, V>?
): TreeNode<T, V> {
var maxRightKey = rightKey
if (leftNode != null) {
val rightKeyCompared = maxRightKey.compareTo(leftNode.maxRightKey)
maxRightKey = if (rightKeyCompared > 0) maxRightKey else leftNode.maxRightKey
}
if (rightNode != null) {
val rightKeyCompared = maxRightKey.compareTo(rightNode.maxRightKey)
maxRightKey = if (rightKeyCompared > 0) maxRightKey else rightNode.maxRightKey
}
val leftHeight = leftNode?.height ?: 0
val rightHeight = rightNode?.height ?: 0
val height = (leftHeight.toInt()).coerceAtLeast(rightHeight.toInt()) + 1
return TreeNode(
leftKey,
rightKey,
maxRightKey,
value,
leftNode,
rightNode,
height.toByte()
)
}
fun <T : Comparable<T>, V>newInstance(
leftKey: T,
rightKey: T,
value: V,
leftNode: TreeNode<T, V>?,
rightNode: TreeNode<T, V>?
): TreeNode<T, V> {
return newInstance(
leftKey,
rightKey,
IntervalTreeKeyValue(
IntervalRange(leftKey, rightKey),
value,
),
leftNode,
rightNode
)
}
fun <T: Comparable<T>, V>rotateLeftLeft(node: TreeNode<T, V>): TreeNode<T, V> {
// node.leftNode must not be null when this is called.
val leftNode = node.leftNode!!
val leftRight = leftNode.rightNode
val newRight = newInstance(
node.leftKey,
node.rightKey,
node.value,
leftRight,
node.rightNode
)
return newInstance(
leftNode.leftKey,
leftNode.rightKey,
leftNode.value,
leftNode.leftNode,
newRight
)
}
fun <T: Comparable<T>, V>rotateLeftRight(node: TreeNode<T, V>): TreeNode<T, V> {
// node.leftNode must not be null when this is called.
val leftNode = node.leftNode!!
val leftRightNode = leftNode.rightNode ?: return node
val leftRightLeft = leftRightNode.leftNode
val leftRightRight = leftRightNode.rightNode
val newLeftNode = newInstance(
leftNode.leftKey,
leftNode.rightKey,
leftNode.value,
leftNode.leftNode,
leftRightLeft
)
val newRightNode = newInstance(
node.leftKey,
node.rightKey,
node.value,
leftRightRight,
node.rightNode
)
return newInstance(
leftRightNode.leftKey,
leftRightNode.rightKey,
leftRightNode.value,
newLeftNode,
newRightNode
)
}
private fun <T: Comparable<T>, V>rotateRightLeft(node: TreeNode<T, V>): TreeNode<T, V> {
// node.rightNode must not be null when this is called.
val rightNode = node.rightNode!!
val rightLeftNode = rightNode.leftNode ?: return node
val rightLeftLeft = rightLeftNode.leftNode
val rightLeftRight = rightLeftNode.rightNode
val newLeftNode = newInstance(
node.leftKey,
node.rightKey,
node.value,
node.leftNode,
rightLeftLeft
)
val newRightNode = newInstance(
rightNode.leftKey,
rightNode.rightKey,
rightNode.value,
rightLeftRight,
rightNode.rightNode
)
return newInstance(
rightLeftNode.leftKey,
rightLeftNode.rightKey,
rightLeftNode.value,
newLeftNode,
newRightNode
)
}
private fun<T: Comparable<T>, V>rotateRightRight(node: TreeNode<T, V>): TreeNode<T, V> {
// node.rightNode must not be null when this is called.
val rightNode = node.rightNode!!
val rightLeft = rightNode.leftNode
val newLeft = newInstance(
node.leftKey,
node.rightKey,
node.value,
node.leftNode,
rightLeft
)
return newInstance(
rightNode.leftKey,
rightNode.rightKey,
rightNode.value,
newLeft,
rightNode.rightNode
)
}
fun<T: Comparable<T>, V>rotateIfNecessary(node: TreeNode<T, V>): TreeNode<T, V> {
val topWeight = node.weight()
if (-1 <= topWeight && topWeight <= 1) {
return node
}
if (topWeight < -1) {
val leftNode = node.leftNode ?: return node
return if (leftNode.weight() <= 0) {
rotateLeftLeft(node)
} else {
rotateLeftRight(node)
}
} else {
// We're right-heavy
val rightNode = node.rightNode ?: return node
return if (rightNode.weight() >= 0) {
rotateRightRight(node)
} else {
rotateRightLeft(node)
}
}
}
}
fun weight(): Int {
val leftHeight = this.leftNode?.height ?: 0
val rightHeight = this.rightNode?.height ?: 0
return rightHeight - leftHeight
}
fun lookupExactRange(rangeLow: T, rangeHigh: T): V? {
val rangeCompare = compareRanges(this.leftKey, this.rightKey, rangeLow, rangeHigh)
if (rangeCompare == 0) {
return this.value.value
}
if (rangeCompare > 0) {
// We were greater than range, so look left
val leftNode = this.leftNode ?: return null
return leftNode.lookupExactRange(rangeLow, rangeHigh)
} else {
// We were less than range, so look right
val rightNode = this.rightNode ?: return null
return rightNode.lookupExactRange(rangeLow, rangeHigh)
}
}
fun put(rangeLow: T, rangeHigh: T, value: V): TreeNode<T, V> {
val rangeCompare = compareRanges(this.leftKey, this.rightKey, rangeLow, rangeHigh)
if (rangeCompare == 0) {
// We'll have to replace ourselves. Since the keys are equal
// no re-balancing is necessary.
return newInstance(rangeLow, rangeHigh, value, this.leftNode, this.rightNode)
} else if (rangeCompare > 0) {
// Range is less than us, look left.
val newLeft = if (this.leftNode == null) {
newInstance(rangeLow, rangeHigh, value, null, null)
} else {
this.leftNode.put(rangeLow, rangeHigh, value)
}
return rotateIfNecessary(newInstance(
this.leftKey,
this.rightKey,
this.value,
newLeft,
this.rightNode
))
} else {
// Range is greater than us, look right.
val newRight = if (this.rightNode == null) {
newInstance(rangeLow, rangeHigh, value, null, null)
} else {
this.rightNode.put(rangeLow, rangeHigh, value)
}
return rotateIfNecessary(newInstance(
this.leftKey,
this.rightKey,
this.value,
this.leftNode,
newRight
))
}
}
private fun extractRightmostChild(): Pair<TreeNode<T, V>?, TreeNode<T, V>> {
if (this.rightNode == null) {
// We are the rightmost child.
// We don't need to re-balance here; right was null
// and left was "balanced enough", so we can only ever
// start from a position of -1 and consequently end up
// at a position of 0.
return Pair(this.leftNode, this)
} else {
val result = this.rightNode.extractRightmostChild()
val newRightNode = result.first
val rightmostChild = result.second
// We might need to re-balance here. However, we
// only need to rotate in either the left-left or
// left-right case, as only the right subtree will
// be possibly reduced in height.
val maybeReplacementNode = newInstance(
this.leftKey,
this.rightKey,
this.value,
this.leftNode,
newRightNode
)
if (maybeReplacementNode.weight() >= -1 || maybeReplacementNode.leftNode == null) {
return Pair(maybeReplacementNode, rightmostChild)
}
return if (maybeReplacementNode.leftNode.weight() <= 0) {
Pair(rotateLeftLeft(maybeReplacementNode), rightmostChild)
} else {
Pair(rotateLeftRight(maybeReplacementNode), rightmostChild)
}
}
}
fun remove(rangeLow: T, rangeHigh: T): TreeNode<T, V>? {
val rangeCompare = compareRanges(this.leftKey, this.rightKey, rangeLow, rangeHigh)
val leftNode = this.leftNode
val rightNode = this.rightNode
if (rangeCompare == 0) {
if (leftNode != null) {
val liftRightmostResult = leftNode.extractRightmostChild()
val newLeft = liftRightmostResult.first
val newTop = liftRightmostResult.second
return rotateIfNecessary(newInstance(
newTop.leftKey,
newTop.rightKey,
newTop.value,
newLeft,
rightNode
))
} else {
// We were balanced to begin with, so if leftNode is null, rightNode can have a height
// of at most 1. Note that rightNode can also be null, which means that the result
// should be null anyway.
return rightNode
}
} else if (rangeCompare > 0) {
if (leftNode == null) {
return this
}
val newLeft = leftNode.remove(rangeLow, rangeHigh)
if (newLeft === leftNode) {
return this
}
return rotateIfNecessary(newInstance(
this.leftKey,
this.rightKey,
this.value,
newLeft,
rightNode
))
} else {
if (rightNode == null) {
return this
}
val newRight = rightNode.remove(rangeLow, rangeHigh)
if (newRight === rightNode) {
return this
}
return rotateIfNecessary(newInstance(
this.leftKey,
this.rightKey,
this.value,
leftNode,
newRight
))
}
}
}
private enum class IntervalTreeIteratorNextStep { SELF, RIGHT }
private data class IntervalTreeIteratorState<T: Comparable<T>, V> (
val node: TreeNode<T, V>,
var nextStep: IntervalTreeIteratorNextStep
)
private abstract class IntervalTreeCommonIterator<T : Comparable<T>, V, R>(
private val t: IntervalTree<T, V>
): Iterator<R> {
protected val iterationStack: ArrayListStack<IntervalTreeIteratorState<T, V>> = ArrayListStack()
private var nextUp: R? = null
private var didInitialPush = false
private fun initialPushIfNecessary() {
// Note that we can't do this in the constructor;
// subclasses implement functionality that we'd call before _their_ constructor ran.
if (this.didInitialPush) {
return
}
if (this.t.root != null) {
this.pushIterationEntry(this.t.root)
this.computeNextUp()
}
this.didInitialPush = true
}
private fun pushIterationEntry(n: TreeNode<T, V>) {
var curNode: TreeNode<T, V>? = n
while (curNode != null && this.iterateLeft(curNode)) {
this.iterationStack.push(IntervalTreeIteratorState(curNode, IntervalTreeIteratorNextStep.SELF))
curNode = curNode.leftNode
}
}
private fun computeNextUp() {
// We can't quite do this in .next() because of how .next()
// is expected to work. .next() should always return and never
// throw if .hasNext() == true, but there are definitely cases
// where we're deep in the iteration stack and have no idea
// whether we're returning or not
var cur = this.iterationStack.peek()
while (cur != null) {
val curNode = cur.node
if (cur.nextStep == IntervalTreeIteratorNextStep.SELF) {
if (this.yieldNode(curNode)) {
cur.nextStep = IntervalTreeIteratorNextStep.RIGHT
this.nextUp = this.transformNode(curNode)
return
}
}
// cur.nextStep == IntervalTreeIteratorNextStep.RIGHT
this.iterationStack.pop()
if (curNode.rightNode != null && this.iterateRight(curNode)) {
this.pushIterationEntry(curNode.rightNode)
}
cur = this.iterationStack.peek()
}
this.nextUp = null
}
override fun hasNext(): Boolean {
this.initialPushIfNecessary()
return this.nextUp != null
}
abstract fun yieldNode(n: TreeNode<T, V>): Boolean
abstract fun transformNode(n: TreeNode<T, V>): R
abstract fun iterateRight(n: TreeNode<T, V>): Boolean
abstract fun iterateLeft(n: TreeNode<T, V>): Boolean
override fun next(): R {
this.initialPushIfNecessary()
val ret = this.nextUp ?: throw NoSuchElementException()
this.computeNextUp()
return ret
}
}
private abstract class IntervalTreePairIterator<T : Comparable<T>, V>(
t: IntervalTree<T, V>
) : IntervalTreeCommonIterator<T, V, IntervalTreeKeyValue<T, V>>(t) {
override fun transformNode(n: TreeNode<T, V>): IntervalTreeKeyValue<T, V> {
return n.value
}
}
private class IntervalTreePointLookupIterator<T: Comparable<T>, V>(
t: IntervalTree<T, V>,
private val lookup: T
) : IntervalTreePairIterator<T, V>(t) {
override fun iterateLeft(n: TreeNode<T, V>): Boolean {
return this.lookup <= n.maxRightKey
}
override fun iterateRight(n: TreeNode<T, V>): Boolean {
return this.lookup <= n.maxRightKey
}
override fun yieldNode(n: TreeNode<T, V>): Boolean {
return n.leftKey <= this.lookup && this.lookup <= n.rightKey
}
}
private class IntervalTreeRangeLookupIterator<T: Comparable<T>, V>(
t: IntervalTree<T, V>,
val lookupLow: T,
val lookupHigh: T
) : IntervalTreePairIterator<T, V>(t) {
private fun rangeOverlaps(otherLow: T, otherHigh: T): Boolean {
return rangeOverlaps(this.lookupLow, this.lookupHigh, otherLow, otherHigh)
}
override fun iterateLeft(n: TreeNode<T, V>): Boolean {
return this.lookupLow <= n.maxRightKey
}
override fun iterateRight(n: TreeNode<T, V>): Boolean {
return this.rangeOverlaps(n.leftKey, n.maxRightKey)
}
override fun yieldNode(n: TreeNode<T, V>): Boolean {
return this.rangeOverlaps(n.leftKey, n.rightKey)
}
}
private class IntervalTreeIterator<T : Comparable<T>, V>(
t: IntervalTree<T, V>
) : IntervalTreeCommonIterator<T, V, IntervalTreeKeyValueWithNodeBalance<T, V>>(t) {
override fun iterateLeft(n: TreeNode<T, V>): Boolean {
return true
}
override fun iterateRight(n: TreeNode<T ,V>): Boolean {
return true
}
override fun yieldNode(n: TreeNode<T, V>): Boolean {
return true
}
override fun transformNode(n: TreeNode<T, V>): IntervalTreeKeyValueWithNodeBalance<T, V> {
val (key, value) = n.value
return IntervalTreeKeyValueWithNodeBalance(key, value, n.weight())
}
}
private fun <T: Comparable<T>, V> sizeTreePairFromIterable(
entries: Iterable<Pair<IntervalRange<T>, V>>
): Pair<TreeNode<T, V>?, Long> {
val it = entries.iterator()
var root: TreeNode<T, V>
var size: Long = 1
if (it.hasNext()) {
val (key, value) = it.next()
root = TreeNode.newInstance(
key,
value,
null,
null
)
} else {
return Pair(null, 0)
}
for ((key, value) in it) {
val (lowerBound, upperBound) = key
val prior = root.lookupExactRange(lowerBound, upperBound)
root = root.put(lowerBound, upperBound, value)
if (prior == null) {
size += 1
}
}
return Pair(root, size)
}
private enum class IntervalTreeInOrderIteratorNextStep { SELF, LEFT, RIGHT, DONE }
private data class IntervalTreeInOrderIteratorState<T: Comparable<T>, V> (
val node: TreeNode<T, V>,
val nextStep: IntervalTreeInOrderIteratorNextStep,
val fromDirection: String
)
private class InOrderIterator<T: Comparable<T>, V>(
tree: IntervalTree<T, V>
): Iterator<Triple<IntervalRange<T>, V, Pair<Int, String>>> {
private val iterationStack: ArrayListStack<IntervalTreeInOrderIteratorState<T, V>> = ArrayListStack()
private var nextUp: Triple<IntervalRange<T>, V, Pair<Int, String>>? = null
init {
if (tree.root != null) {
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
tree.root,
IntervalTreeInOrderIteratorNextStep.SELF,
"root"
)
)
this.computeNextUp()
}
}
private fun computeNextUp() {
// We can't quite do this in .next() because of how .next()
// is expected to work. .next() should always return and never
// throw if .hasNext() == true, but there are definitely cases
// where we're deep in the iteration stack and have no idea
// whether we're returning or not
while (this.iterationStack.size > 0) {
val cur = this.iterationStack.pop()!!
val curNode = cur.node
if (cur.nextStep == IntervalTreeInOrderIteratorNextStep.DONE) {
continue
}
if (cur.nextStep == IntervalTreeInOrderIteratorNextStep.SELF) {
val (key, value) = curNode.value
this.nextUp = Triple(key, value, Pair(this.iterationStack.size, cur.fromDirection))
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
curNode,
IntervalTreeInOrderIteratorNextStep.LEFT,
cur.fromDirection
)
)
return
}
if (cur.nextStep == IntervalTreeInOrderIteratorNextStep.LEFT && curNode.leftNode != null) {
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
curNode,
IntervalTreeInOrderIteratorNextStep.RIGHT,
cur.fromDirection
)
)
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
curNode.leftNode,
IntervalTreeInOrderIteratorNextStep.SELF,
"left"
)
)
continue
}
// cur.nextStep == IntervalTreeInOrderIteratorNextStep.RIGHT
if (curNode.rightNode != null) {
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
curNode,
IntervalTreeInOrderIteratorNextStep.DONE,
cur.fromDirection
)
)
this.iterationStack.push(
IntervalTreeInOrderIteratorState(
curNode.rightNode,
IntervalTreeInOrderIteratorNextStep.SELF,
"right"
)
)
continue
}
}
this.nextUp = null
}
override fun hasNext(): Boolean {
return this.nextUp != null
}
override fun next(): Triple<IntervalRange<T>, V, Pair<Int, String>> {
val ret = this.nextUp ?: throw NoSuchElementException()
this.computeNextUp()
return ret
}
}
private fun<T: Comparable<T>, V> visitFromIterator(
node: TreeNode<T, V>,
iterator: IntervalTreePairIterator<T, V>,
receiver: (result: IntervalTreeKeyValue<T, V>) -> Unit
) {
val left = node.leftNode
if (left != null && iterator.iterateLeft(node)) {
visitFromIterator(left, iterator, receiver)
}
if (iterator.yieldNode(node)) {
receiver(iterator.transformNode(node))
}
val right = node.rightNode ?: return
if (iterator.iterateRight(node)) {
visitFromIterator(right, iterator, receiver)
}
}
private fun<T: Comparable<T>, V> visitFromIteratorForFull(
node: TreeNode<T, V>,
iterator: IntervalTreeIterator<T, V>,
receiver: (result: IntervalTreeKeyValueWithNodeBalance<T, V>) -> Unit
) {
val left = node.leftNode
if (left != null) {
// For a full iterator, we always iterate left.
visitFromIteratorForFull(left, iterator, receiver)
}
// For a full iterator, we always yield.
receiver(iterator.transformNode(node))
val right = node.rightNode ?: return
// For a full iterator, we always iterate right.
visitFromIteratorForFull(right, iterator, receiver)
}
/**
* A persistent, immutable associative map from keys of ordered pairs to arbitrary values.
*
* An IntervalTree stores values for ranges of keys, and supports lookups either by key ranges overlapping
* a point, or key ranges overlapping another range. The semantics of "overlapping" are described in
* [IntervalRange.overlaps].
*/
class IntervalTree<T: Comparable<T>, V> private constructor(
internal val root: TreeNode<T, V>?,
val size: Long,
): Iterable<IntervalTreeKeyValueWithNodeBalance<T, V>> {
constructor(): this(null, 0)
private constructor(treeSizePair: Pair<TreeNode<T, V>?, Long>): this(treeSizePair.first, treeSizePair.second)
constructor(entries: Iterable<Pair<IntervalRange<T>, V>>) : this(sizeTreePairFromIterable(entries))
/**
* Returns an iterator over all key/value pairs contained in this [IntervalTree] whose key ranges
* contain [at].
*
* [at] can be considered an [IntervalRange] where both the [IntervalRange.lowerBound] and
* [IntervalRange.upperBound] are equal to [at], and "contains" is a synonym for
* [IntervalRange.overlaps].
*/
fun lookupPoint(at: T): Iterator<IntervalTreeKeyValue<T, V>> {
return IntervalTreePointLookupIterator(this, at)
}
/**
* Calls [receiver] with every key/value pair contained in this [IntervalTree] whose key ranges
* contain [at].
*
* [at] can be considered an [IntervalRange] where both the [IntervalRange.lowerBound] and
* [IntervalRange.upperBound] are equal to [at], and "contains" is a synonym for
* [IntervalRange.overlaps].
*/
fun lookupPointVisit(at: T, receiver: (value: IntervalTreeKeyValue<T, V>) -> Unit) {
val root = this.root ?: return
visitFromIterator(root, IntervalTreePointLookupIterator(this, at), receiver)
}
/**
* Returns an iterator over all key/value pairs contained in this [IntervalTree] whose key ranges
* overlap [range].
*
* The semantics of "overlap" are described in [IntervalRange.overlaps].
*/
fun lookupRange(range: IntervalRange<T>): Iterator<IntervalTreeKeyValue<T, V>> {
return IntervalTreeRangeLookupIterator(this, range.lowerBound, range.upperBound)
}
/**
* Calls [receiver] with every key/value pair contained in this [IntervalTree] whose key ranges
* overlap [range].
*
* The semantics of "overlap" are described in [IntervalRange.overlaps].
*/
fun lookupRangeVisit(range: IntervalRange<T>, receiver: (value: IntervalTreeKeyValue<T, V>) -> Unit) {
val root = this.root ?: return
visitFromIterator(root, IntervalTreeRangeLookupIterator(this, range.lowerBound, range.upperBound), receiver)
}
/**
* Returns the value corresponding to the key exactly equal to [range], if such a value is contained in this
* [IntervalTree], or `null` otherwise.
*/
fun lookupExactRange(range: IntervalRange<T>): V? {
return this.root?.lookupExactRange(range.lowerBound, range.upperBound)
}
/**
* Returns a new [IntervalTree] containing all of this IntervalTree's key/value pairs, excepting the key/value
* pair where the key is equal to [range] if such a pair exists, but with an additional key/value pair mapping
* the key `range` to [value].
*
* If a key/value pair exists for `range` in this IntervalTree, and the `value` for this pair is identical
* to the given `value`, the result will be this IntervalTree. This is permissible because the resulting
* IntervalTree would otherwise be equivalent.
*/
fun put(range: IntervalRange<T>, value: V): IntervalTree<T, V> {
val root = this.root ?: return IntervalTree(
TreeNode.newInstance(
range,
value,
null,
null
),
1,
)
val preexisting = this.lookupExactRange(range)
if (preexisting === value) {
return this
}
return IntervalTree(
root.put(range.lowerBound, range.upperBound, value),
if (preexisting == null) { this.size + 1 } else { this.size },
)
}
/**
* Returns a new [IntervalTree] containing all of this IntervalTree's key/value pairs, excepting the key/value
* pair where the key is equal to [range] if such a pair exists.
*
* If a key/value pair does not exist for `range` in this IntervalTree, the resulting value will be this
* IntervalTree. This is permissible because the resulting IntervalTree would otherwise be equivalent.
*/
fun remove(range: IntervalRange<T>): IntervalTree<T, V> {
val root = this.root ?: return this
val removedRoot = root.remove(range.lowerBound, range.upperBound)
return if (removedRoot === root) {
this
} else {
IntervalTree(removedRoot, this.size - 1)
}
}
/**
* Calls [updater] with the key/value pair contained in this [IntervalTree] where the key is equal to [range],
* if such a pair exists, or `null` otherwise, and returns a new IntervalTree with the updated results.
*
* `updater` may return `null`; in this case, the key/value pair for the given `range` is removed from the resulting
* IntervalTree.
*
* Semantics for the return value are described in [IntervalTree.put] for the case of the non-null return from
* `updater`, and in [IntervalTree.remove] for the case of the null return from `updater`.
*/
fun update(range: IntervalRange<T>, updater: (value: V?) -> V?): IntervalTree<T, V> {
val prev = this.lookupExactRange(range)
val repl = updater(prev)
if (prev === repl) {
return this
}
val removed = this.remove(range)
return if (repl == null) {
removed
} else {
removed.put(range, repl)
}
}
override fun iterator(): Iterator<IntervalTreeKeyValueWithNodeBalance<T, V>> {
return IntervalTreeIterator(this)
}
/**
* Calls [receiver] with every key/value pair in this [IntervalTree].
*/
fun visitAll(receiver: (value: IntervalTreeKeyValueWithNodeBalance<T, V>) -> Unit) {
val root = this.root ?: return
visitFromIteratorForFull(root, IntervalTreeIterator(this), receiver)
}
// This is only used for testing purposes.
internal fun inOrderIterator(): Iterator<Triple<IntervalRange<T>, V, Pair<Int, String>>> {
return InOrderIterator(this)
}
/**
* Returns the [IntervalRange] with the minimum [IntervalRange.lowerBound] in this [IntervalTree], or
* `null` if this IntervalTree does not contain any entries.
*/
fun minRange(): IntervalRange<T>? {
var cur = this.root
while (cur != null) {
if (cur.leftNode != null) {
cur = cur.leftNode
} else {
return IntervalRange(cur.leftKey, cur.rightKey)
}
}
return null
}
/**
* Returns the [IntervalRange] with the maximum [IntervalRange.lowerBound] in this [IntervalTree], or
* `null` if this IntervalTree does not contain any entries.
*/
fun maxRange(): IntervalRange<T>? {
var cur = this.root
while (cur != null) {
if (cur.rightNode != null) {
cur = cur.rightNode
} else {
return IntervalRange(cur.leftKey, cur.rightKey)
}
}
return null
}
} | 5 | Kotlin | 0 | 0 | 023dd1f3cd231f9f62c7e349dd1f59079515364d | 37,104 | sidereal | MIT License |
src/Day01.kt | Kvest | 573,621,595 | false | {"Kotlin": 87988} | fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
private fun part1(input: List<String>): Int {
return input.toCalories().maxOrNull() ?: 0
}
private fun part2(input: List<String>): Int {
return input
.toCalories()
.sorted()
.takeLast(3)
.sum()
}
private fun List<String>.toCalories(): List<Int> {
val result = mutableListOf<Int>()
var current = 0
this.forEach { row ->
if (row.isEmpty()) {
result.add(current)
current = 0
} else {
current += row.toInt()
}
}
result.add(current)
return result
}
| 0 | Kotlin | 0 | 0 | 6409e65c452edd9dd20145766d1e0ea6f07b569a | 867 | AOC2022 | Apache License 2.0 |
contents/thomas_algorithm/code/kotlin/thomas.kt | algorithm-archivists | 81,649,789 | false | {"Python": 61641, "Assembly": 60055, "C++": 56073, "Julia": 54791, "C": 49744, "Java": 40529, "Rust": 36123, "C#": 26237, "Haskell": 21852, "Common Lisp": 20798, "JavaScript": 18939, "TeX": 14910, "Go": 13136, "PHP": 9196, "Elm": 9135, "Clojure": 8693, "Fortran": 8124, "Gnuplot": 7573, "Swift": 7229, "OCaml": 7226, "Scala": 6842, "MATLAB": 6758, "Nim": 5503, "Dockerfile": 5413, "Lua": 5179, "Ruby": 4845, "Shell": 4437, "TypeScript": 4266, "Crystal": 4111, "Kotlin": 4098, "PowerShell": 4032, "Witcher Script": 3098, "V": 2741, "Smalltalk": 2666, "Racket": 1695, "Dart": 1597, "D": 1462, "LOLCODE": 1262, "Factor": 1178, "Scheme": 1032, "R": 958, "CSS": 898, "Vim Script": 583} | private fun thomas(a: DoubleArray, b: DoubleArray, c: DoubleArray, d: DoubleArray): DoubleArray {
val cPrime = c.clone()
val x = d.clone()
val size = a.size
cPrime[0] /= b[0]
x[0] /= b[0]
for (i in 1 until size) {
val scale = 1.0 / (b[i] - cPrime[i - 1] * a[i])
cPrime[i] *= scale
x[i] = (x[i] - a[i] * x[i - 1]) * scale
}
for (i in (size - 2) downTo 0) {
x[i] -= cPrime[i] * x[i + 1]
}
return x
}
fun main(args: Array<String>) {
val a = doubleArrayOf(0.0, 2.0, 3.0)
val b = doubleArrayOf(1.0, 3.0, 6.0)
val c = doubleArrayOf(4.0, 5.0, 0.0)
val x = doubleArrayOf(7.0, 5.0, 3.0)
val solution = thomas(a, b, c, x)
println("System:")
println("[%.1f, %.1f, %.1f][x] = [%.1f]".format(b[0], c[0], 0f, x[0]))
println("[%.1f, %.1f, %.1f][y] = [%.1f]".format(a[1], b[1], c[1], x[1]))
println("[%.1f, %.1f, %.1f][z] = [%.1f]\n".format(0f, a[2], b[2], x[2]))
println("Solution:")
for (i in solution.indices) {
println("[% .5f]".format(solution[i]))
}
}
| 98 | Python | 390 | 2,240 | 38c40e075d8a454f97aca03624d4ce398d16470a | 1,072 | algorithm-archive | MIT License |
src/main/kotlin/com/hj/leetcode/kotlin/problem947/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem947
/**
* LeetCode page: [947. Most Stones Removed with Same Row or Column](https://leetcode.com/problems/most-stones-removed-with-same-row-or-column/);
*/
class Solution {
/* Complexity:
* Time O(N) and Space O(N) where N is the size of stones;
*/
fun removeStones(stones: Array<IntArray>): Int {
return stones.size - numConnectedComponents(stones)
}
private fun numConnectedComponents(stones: Array<IntArray>): Int {
var result = 0
val visited = BooleanArray(stones.size)
val indicesByRow = stones.indices.groupBy { stones[it][0] }
val indicesByColumn = stones.indices.groupBy { stones[it][1] }
for (index in stones.indices) {
if (visited[index]) {
continue
}
result++
val dfsStack = ArrayDeque<Int>()
dfsStack.addLast(index)
visited[index] = true
while (dfsStack.isNotEmpty()) {
val poppedIndex = dfsStack.removeLast()
val (row, column) = stones[poppedIndex]
val nextIndices = listOf(
checkNotNull(indicesByRow[row]),
checkNotNull(indicesByColumn[column])
).asSequence().flatten()
for (nextIndex in nextIndices) {
if (!visited[nextIndex]) {
dfsStack.addLast(nextIndex)
visited[nextIndex] = true
}
}
}
}
return result
}
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,599 | hj-leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/nl/dirkgroot/adventofcode/year2020/Day07.kt | dirkgroot | 317,968,017 | false | {"Kotlin": 187862} | package nl.dirkgroot.adventofcode.year2020
import nl.dirkgroot.adventofcode.util.Input
import nl.dirkgroot.adventofcode.util.Puzzle
class Day07(input: Input) : Puzzle() {
private val rules by lazy { parseBagRules(input.lines()) }
private fun parseBagRules(input: List<String>) = input.map(this::parseBagRule).toMap()
private fun parseBagRule(rule: String): Pair<String, Map<String, Int>> {
val (bagColor, bagContentRules) = sanitizeBagRule(rule).split("bagscontain")
return bagColor to parseBagContentRules(bagContentRules)
}
private fun sanitizeBagRule(rule: String) = rule.replace("[,.\\s]+".toRegex(), "")
private fun parseBagContentRules(bagContentRules: String) = bagContentRules
.split("bags?".toRegex())
.filter { it.isNotBlank() && it != "noother" }
.map { it.takeLastWhile { c -> !c.isDigit() } to it.takeWhile { c -> c.isDigit() }.toInt() }
.toMap()
override fun part1() = rules.count { canContainColor(it.key, "shinygold") }
private fun canContainColor(containerColor: String, bagColor: String): Boolean = rules[containerColor]!!
.keys.any { color -> color == bagColor || canContainColor(color, bagColor) }
override fun part2() = bagsNeeded("shinygold")
private fun bagsNeeded(containerColor: String): Int = rules[containerColor]!!
.map { (innerBagColor, count) -> count + bagsNeeded(innerBagColor) * count }
.sum()
} | 1 | Kotlin | 1 | 1 | ffdffedc8659aa3deea3216d6a9a1fd4e02ec128 | 1,451 | adventofcode-kotlin | MIT License |
calendar/day07/Day7.kt | maartenh | 572,433,648 | false | {"Kotlin": 50914} | package day07
import Day
import Lines
class Day7 : Day() {
override fun part1(input: Lines): Any {
val fsTree = buildFS(input)
return fsTree.allDirectories
.map(Directory::size)
.filter { it <= 100_000 }
.sum()
}
override fun part2(input: Lines): Any {
val diskSize = 70_000_000
val requiredSpace = 30_000_000
val fsTree = buildFS(input)
val freeSpace = diskSize - fsTree.size
val neededSpace = requiredSpace - freeSpace
return fsTree.allDirectories
.map(Directory::size)
.filter { it >= neededSpace }
.min()
}
private fun buildFS(input: Lines): Directory {
val root = Directory("/")
var currentDir = root
val pathToCurrent = mutableListOf<Directory>()
input.forEach {
when {
it == "$ ls" -> {}
it == "$ cd /" -> {
currentDir = root
pathToCurrent.clear()
}
it == "$ cd .." -> {
currentDir = pathToCurrent.last()
pathToCurrent.removeLast()
}
it.startsWith("$ cd ") -> {
val dirName = it.substring(5)
pathToCurrent.add(currentDir)
currentDir = currentDir.directories.find { dir -> dir.name == dirName }!!
}
it.startsWith("dir ") -> {
currentDir.directories.add(Directory(it.substring(4)))
}
it[0].isDigit() -> {
val splitter = it.indexOf(' ')
val size = it.substring(0, splitter).toInt()
val name = it.substring(splitter + 1)
currentDir.files.add(File(name, size))
}
else -> {
throw AssertionError("Unhandled input line: $it")
}
}
}
return root
}
}
data class File(val name: String, val size: Int)
data class Directory(
val name: String,
val directories: MutableList<Directory> = mutableListOf(),
val files: MutableList<File> = mutableListOf()
) {
private var dirSize: Int? = null
val size: Int
get() {
if (dirSize == null) {
dirSize = files.map(File::size).sum() + directories.map(Directory::size).sum()
}
return dirSize!!
}
val allDirectories: List<Directory>
get() = listOf(this) + directories.flatMap(Directory::allDirectories)
} | 0 | Kotlin | 0 | 0 | 4297aa0d7addcdc9077f86ad572f72d8e1f90fe8 | 2,646 | advent-of-code-2022 | Apache License 2.0 |
src/questions/DivideTwoIntegers.kt | realpacific | 234,499,820 | false | null | package questions
import _utils.UseCommentAsDocumentation
import algorithmdesignmanualbook.print
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.test.assertEquals
/**
* Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator.
* Return the quotient after dividing dividend by divisor.
* The integer division should truncate toward zero, which means losing its fractional part.
* For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.
*
* Note: Assume we are dealing with an environment that could only store integers
* within the 32-bit signed integer range: [−2^31, 2^31 − 1].
* For this problem, assume that your function returns 2^31 − 1 when the division result overflows.
*
* https://leetcode.com/problems/divide-two-integers/
*/
@UseCommentAsDocumentation
private fun divide(dividend: Int, divisor: Int): Int {
if (dividend == 0) return 0
if (divisor == 1) return dividend
if (dividend == Integer.MIN_VALUE && divisor == -1) {
// overflow
return Integer.MAX_VALUE
}
val neg = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)
// Convert to long because -2,147,483,648 .. 2,147,483,647 i.e abs(MIN) doesn't fit on int
var m = abs(dividend.toLong())
val n = abs(divisor.toLong())
var result = 0
while (m >= n) {
m -= n
result++
}
// Can't multiply
// Negate using (* -1)
// https://stackoverflow.com/a/64325038/8389034
result = if (neg) result.inv() + 1 else (result)
return result
}
fun main() {
assertEquals(-1073741824, divide(dividend = -2147483648, divisor = 2).print())
assertEquals(-2147483648, divide(dividend = -2147483648, divisor = 1).print())
assertEquals(2147483647, divide(dividend = -2147483648, divisor = -1).print())
assertEquals(-2, divide(dividend = 7, divisor = -3).print())
assertEquals(-1, divide(dividend = 1, divisor = -1).print())
assertEquals(-1, divide(dividend = -1, divisor = 1).print())
assertEquals(3, divide(dividend = 10, divisor = 3).print())
assertEquals(10, divide(dividend = 50, divisor = 5).print())
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 2,207 | algorithms | MIT License |
kotlin/src/katas/kotlin/adventofcode/day2/Part1.kt | dkandalov | 2,517,870 | false | {"Roff": 9263219, "JavaScript": 1513061, "Kotlin": 836347, "Scala": 475843, "Java": 475579, "Groovy": 414833, "Haskell": 148306, "HTML": 112989, "Ruby": 87169, "Python": 35433, "Rust": 32693, "C": 31069, "Clojure": 23648, "Lua": 19599, "C#": 12576, "q": 11524, "Scheme": 10734, "CSS": 8639, "R": 7235, "Racket": 6875, "C++": 5059, "Swift": 4500, "Elixir": 2877, "SuperCollider": 2822, "CMake": 1967, "Idris": 1741, "CoffeeScript": 1510, "Factor": 1428, "Makefile": 1379, "Gherkin": 221} | package katas.kotlin.adventofcode.day2
import nonstdlib.*
import java.io.*
fun main() {
val text = File("src/katas/kotlin/adventofcode/day2/input.txt").readText()
val program = text.split(",").map(String::toInt).toMutableList()
println(execute(ArrayList(program), programInput1 = 12, programInput2 = 2))
}
fun execute(program: MutableList<Int>, programInput1: Int, programInput2: Int): Int {
program[1] = programInput1
program[2] = programInput2
val commands = toCommands(program)
for (it in commands) {
if (it is Halt) break
it.printed().execute(program)
}
return program[0]
}
private fun toCommands(tokens: List<Int>, shift: Int = 0): List<Command> {
if (shift >= tokens.size) return emptyList()
return when (tokens[shift]) {
1 -> listOf(Add(
input1 = tokens[shift + 1],
input2 = tokens[shift + 2],
output = tokens[shift + 3]
)) + toCommands(tokens, shift + 4)
2 -> listOf(Multiply(
input1 = tokens[shift + 1],
input2 = tokens[shift + 2],
output = tokens[shift + 3]
)) + toCommands(tokens, shift + 4)
99 -> listOf(Halt) + toCommands(tokens, shift + 1)
else -> error("Unexpected command ${tokens[shift]}")
}
}
interface Command {
fun execute(program: MutableList<Int>)
}
data class Add(val input1: Int, val input2: Int, val output: Int): Command {
override fun execute(program: MutableList<Int>) {
program[output] = program[input1] + program[input2]
}
}
data class Multiply(val input1: Int, val input2: Int, val output: Int): Command {
override fun execute(program: MutableList<Int>) {
program[output] = program[input1] * program[input2]
}
}
object Halt: Command {
override fun execute(program: MutableList<Int>) {
error("")
}
override fun toString() = "Halt"
} | 7 | Roff | 3 | 5 | 0f169804fae2984b1a78fc25da2d7157a8c7a7be | 1,911 | katas | The Unlicense |
src/Day01.kt | Excape | 572,551,865 | false | {"Kotlin": 36421} | fun main() {
fun getSumOfCalories(input: List<String>): List<Int> = input.fold(mutableListOf(0)) { acc, line ->
when {
line.isBlank() -> acc.add(0)
else -> acc[acc.lastIndex] += line.toInt()
}
return@fold acc
}
fun part1(input: List<String>): Int = getSumOfCalories(input).max()
fun part2(input: List<String>): Int = getSumOfCalories(input).sortedDescending().take(3).sum()
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("Day01")
println("part 1: ${part1(input)}")
println("part 2: ${part2(input)}")
}
| 0 | Kotlin | 0 | 0 | a9d7fa1e463306ad9ea211f9c037c6637c168e2f | 676 | advent-of-code-2022 | Apache License 2.0 |
libraries/formula/src/FormulaParser.kt | featurea | 407,517,337 | false | null | package featurea.formula
private const val operatorSymbols = "+-*/<=>"
fun Char.isOperatorSymbol() = operatorSymbols.contains(this)
val operatorMap = mapOf<String, () -> FormulaOperator<*, *, *>>(
"+" to { Plus() },
"-" to { Minus() },
"*" to { Multiply() },
"/" to { Divide() },
"==" to { Equal() },
">" to { Greater() },
">=" to { GreaterOrEqual() },
"<" to { Less() },
"<=" to { LessOrEqual() }
)
private val operatorComparator = Comparator<FormulaOperator<*, *, *>> { operator1, operator2 ->
when {
(operator1::class == operator2::class) -> 0
operator1.isBoolean -> 1
operator1.isNonLinear -> -1
operator1.isLinear -> if (operator2.isBoolean) {
-1
} else {
1
}
else -> throw error("Opoerator not defined")
}
}
fun ArrayList<FormulaOperator<Any, Any, Any>>.sortOperators() {
val sortedOperators = sortedWith(operatorComparator)
clear()
addAll(sortedOperators)
}
private val FormulaOperator<*, *, *>.isBoolean get() = this is Equal || this is Less || this is LessOrEqual || this is Greater || this is GreaterOrEqual
private val FormulaOperator<*, *, *>.isLinear get() = this is Plus || this is Minus
private val FormulaOperator<*, *, *>.isNonLinear get() = this is Multiply || this is Divide
| 30 | Kotlin | 1 | 6 | 07074dc37a838f16ece90c19a4e8d45e743013d3 | 1,372 | engine | MIT License |
src/main/kotlin/tr/emreone/adventofcode/days/Day07.kt | EmRe-One | 568,569,073 | false | {"Kotlin": 166986} | package tr.emreone.adventofcode.days
import tr.emreone.kotlin_utils.Logger.logger
import tr.emreone.kotlin_utils.extensions.times
object Day07 {
enum class NodeType {
UNKNOWN,
DIRECTORY,
FILE
}
class FileSystem() {
val root = Node(null, "", NodeType.DIRECTORY)
var currentNode: Node = root
fun pwd(): String {
return pathOf(currentNode)
}
companion object {
fun calcSizeOf(node: Node): Long {
if (node.type == NodeType.FILE) {
return node.weight ?: 0
}
return node.children.sumOf { calcSizeOf(it) }
}
fun pathOf(node: Node): String {
return if (node.parent == null) {
"/"
} else {
pathOf(node.parent) + node.fileName + "/"
}
}
}
}
data class Node(
val parent: Node?,
var fileName: String,
var type: NodeType = NodeType.UNKNOWN,
var weight: Long? = null,
) {
val children = mutableListOf<Node>()
}
private fun parseFileSystem(input: List<String>): FileSystem {
val fileSystem = FileSystem()
var lineIndex = 0
val commandLinePatter = "\\$\\s(cd|ls)\\s?(/|\\w+|..)?".toRegex()
while (lineIndex < input.size) {
var line = input[lineIndex].trim()
if (commandLinePatter.matches(line)) {
val tokens = line.split(" ")
when (tokens[1]) {
"cd" -> {
if (tokens[2] == "/") {
fileSystem.currentNode = fileSystem.root
logger.debug { "navigate to root -> " + fileSystem.pwd() }
} else if (tokens[2] == "..") {
fileSystem.currentNode = fileSystem.currentNode.parent!!
logger.debug { "navigate level up ->" + fileSystem.pwd() }
} else {
val enterNode = tokens[2]
fileSystem.currentNode = fileSystem.currentNode.children.first { it.fileName == enterNode }
logger.debug { "navigate to $enterNode -> " + fileSystem.pwd() }
}
lineIndex++
}
"ls" -> {
lineIndex++
logger.debug { "list files in " + fileSystem.pwd() }
do {
line = input[lineIndex]
if (line.startsWith("dir")) {
val (dirLabel, dirName) = line.split(" ")
fileSystem.currentNode.children.add(
Node(
fileSystem.currentNode,
dirName,
NodeType.DIRECTORY
)
)
logger.debug("add directory to ${fileSystem.pwd()} -> $dirName")
} else {
val (fileSize, fileName) = line.split(" ")
fileSystem.currentNode.children.add(
Node(
fileSystem.currentNode,
fileName,
NodeType.FILE,
fileSize.toLong()
)
)
logger.debug("add file to ${fileSystem.pwd()} -> $fileName")
}
} while (lineIndex + 1 < input.size && !input[++lineIndex].startsWith("$"))
}
}
} else {
lineIndex++
}
}
return fileSystem
}
private fun printNodeWithChildren(node: Node, indent: Int = 0) {
logger.debug { "${" " * indent} - ${if (node.parent == null) "/" else node.fileName}" }
when (node.type) {
NodeType.DIRECTORY -> {
logger.debug { " (dir)\n" }
node.children.forEach { child ->
printNodeWithChildren(child, indent + 2)
}
}
NodeType.FILE -> {
logger.debug { " (file, size=${node.weight})\n" }
}
NodeType.UNKNOWN -> {
// do nothing
}
}
}
fun part1(input: List<String>): Long {
val fileSystem = parseFileSystem(input)
printNodeWithChildren(fileSystem.root, 0)
var total = 0L
fun sumAllDirectoriesWithLowerThanN(node: Node, maxWeight: Long) {
if (node.type == NodeType.DIRECTORY) {
val size = FileSystem.calcSizeOf(node)
if (size < maxWeight) {
total += size
}
node.children.forEach { sumAllDirectoriesWithLowerThanN(it, maxWeight) }
}
}
sumAllDirectoriesWithLowerThanN(fileSystem.root, 100_000L)
return total
}
fun part2(input: List<String>): Long {
val fileSystem = parseFileSystem(input)
val totalSpace = 70_000_000L
val minimumFreeSpace = 30_000_000L
val currentSize = FileSystem.calcSizeOf(fileSystem.root)
val matchingDirs = mutableListOf<Node>()
fun collectMatchingDirectory(node: Node) {
for (child in node.children.filter { it.type == NodeType.DIRECTORY }) {
val size = FileSystem.calcSizeOf(child)
if (currentSize - size < totalSpace - minimumFreeSpace) {
matchingDirs.add(child)
collectMatchingDirectory(child)
}
}
}
collectMatchingDirectory(fileSystem.root)
return matchingDirs.minOf { FileSystem.calcSizeOf(it) }
}
}
| 0 | Kotlin | 0 | 0 | a951d2660145d3bf52db5cd6d6a07998dbfcb316 | 6,217 | advent-of-code-2022 | Apache License 2.0 |
src/day01/Day01.kt | Raibaz | 571,997,684 | false | {"Kotlin": 9423} | fun main() {
fun computeCalories(input: List<String>): MutableMap<Int, Int> {
val calories = mutableMapOf<Int, Int>()
var elfIndex = 0
input.forEach {
if (it.isEmpty()) {
elfIndex++
} else {
var currentCalories = calories[elfIndex] ?: 0
currentCalories += it.toInt()
calories[elfIndex] = currentCalories
}
}
return calories
}
fun part1(input: List<String>): Int {
return computeCalories(input).values.max()
}
fun part2(input: List<String>): Int {
return computeCalories(input).values.sorted().reversed().take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/input_test")
println(part1(testInput))
val input = readInput("day01/input")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 99d912f661bd3545ca9ff222ac7d93c12682f42d | 952 | aoc-22 | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/PowerOfThree.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
import kotlin.math.log10
private const val POWER = 3
fun interface PowerOfThreeStrategy {
fun isPowerOfThree(n: Int): Boolean
}
class POTLoopIteration : PowerOfThreeStrategy {
override fun isPowerOfThree(n: Int): Boolean {
var num = n
if (num < 1) {
return false
}
while (num % POWER == 0) {
num /= POWER
}
return num == 1
}
}
class POTBaseConversion : PowerOfThreeStrategy {
override fun isPowerOfThree(n: Int): Boolean {
return n.toString(POWER).matches("^10*$".toRegex())
}
}
class POTMathematics : PowerOfThreeStrategy {
override fun isPowerOfThree(n: Int): Boolean {
val local = log10(n.toDouble()) / log10(POWER.toDouble())
return local % 1.0 == 0.0
}
}
class POTIntegerLimitations : PowerOfThreeStrategy {
companion object {
private const val LIMIT = 1162261467
}
override fun isPowerOfThree(n: Int): Boolean {
return n > 0 && LIMIT % n == 0
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 1,663 | kotlab | Apache License 2.0 |
src/main/kotlin/days/Day10.kt | butnotstupid | 433,717,137 | false | {"Kotlin": 55124} | package days
import java.util.*
class Day10 : Day(10) {
private val closes = mapOf(
'(' to ')', '[' to ']',
'{' to '}', '<' to '>',
)
private val errorPoints = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137)
private val completionPoints = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4)
override fun partOne(): Any {
return inputList.sumOf { line ->
val stack = Stack<Char>()
var linePoints = 0
for (c in line) {
when (c) {
in closes.keys -> stack.push(c)
closes[stack.peek()] -> stack.pop()
else -> linePoints = errorPoints.getValue(c)
}
if (linePoints != 0) break
}
linePoints
}
}
override fun partTwo(): Any {
val totals = inputList.mapNotNull { line ->
val stack = Stack<Char>()
var validLine = true
for (c in line) {
when (c) {
in closes.keys -> stack.push(c)
closes[stack.peek()] -> stack.pop()
else -> validLine = false
}
if (!validLine) break
}
if (!validLine) null
else {
var linePoints = 0L
for (c in stack.reversed()) {
linePoints = linePoints * 5 + completionPoints.getValue(closes.getValue(c))
}
linePoints
}
}.sorted()
return totals[totals.size / 2]
}
}
| 0 | Kotlin | 0 | 0 | a06eaaff7e7c33df58157d8f29236675f9aa7b64 | 1,609 | aoc-2021 | Creative Commons Zero v1.0 Universal |
year2023/day05/almanac/src/main/kotlin/com/curtislb/adventofcode/year2023/day05/almanac/Almanac.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | package com.curtislb.adventofcode.year2023.day05.almanac
import com.curtislb.adventofcode.common.io.forEachSection
import com.curtislb.adventofcode.common.parse.parseLongs
import java.io.File
/**
* A copy of the Island Island Almanac, which contains [CategoryMap]s for converting integer values
* between various categories.
*
* @property categoryMaps A map from each category in the almanac to a [CategoryMap] that converts
* values of that category to new values of a different category.
*
* @constructor Creates a new [Almanac] instance with the given [categoryMaps].
*/
class Almanac(private val categoryMaps: Map<String, CategoryMap>) {
/**
* Returns the list of values that result from converting the given input [values] from the
* specified [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
fun convertValues(
values: List<Long>,
sourceCategory: String,
targetCategory: String
): List<Long> {
return foldOverCategoryMaps(values, sourceCategory, targetCategory) { result, categoryMap ->
categoryMap.convertValues(result)
}
}
/**
* Returns a list of value ranges that result from converting the given input [ranges] from the
* specified [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
fun convertRanges(
ranges: Set<LongRange>,
sourceCategory: String,
targetCategory: String
): Set<LongRange> {
return foldOverCategoryMaps(ranges, sourceCategory, targetCategory) { result, categoryMap ->
categoryMap.convertRanges(result)
}
}
/**
* Returns the result of applying the specified [operation] to an [initial] value and subsequent
* result values for each category map in the almanac that can be used (in order) to map values
* from [sourceCategory] to [targetCategory].
*
* @throws IllegalArgumentException If [sourceCategory] can't be converted to [targetCategory].
*/
private inline fun <T> foldOverCategoryMaps(
initial: T,
sourceCategory: String,
targetCategory: String,
operation: (result: T, categoryMap: CategoryMap) -> T
): T {
var result = initial
var category = sourceCategory
while (category != targetCategory) {
val categoryMap = categoryMaps[category]
require(categoryMap != null) { "No map for category: $category" }
result = operation(result, categoryMap)
category = categoryMap.targetCategory
}
return result
}
companion object {
/**
* Returns a list of initial values and an [Almanac] read from the given input [file].
*
* The [file] must have the following format:
*
* ```
* $label: $value1 $value2 ... $valueN
*
* $categoryMap1
*
* $categoryMap2
*
* ...
*
* $categoryMapM
* ```
*
* See [CategoryMap.fromLines] for how each `categoryMap` section is formatted.
*
* @throws IllegalArgumentException If [file] is not formatted correctly.
*/
fun parseFile(file: File): Pair<List<Long>, Almanac> {
var values: List<Long> = emptyList()
val categoryMaps = mutableMapOf<String, CategoryMap>()
file.forEachSection { lines ->
if (values.isEmpty()) {
// Read initial values from the first line
values = lines[0].parseLongs()
} else {
// Read category maps from subsequent sections
val categoryMap = CategoryMap.fromLines(lines)
categoryMaps[categoryMap.sourceCategory] = categoryMap
}
}
return Pair(values, Almanac(categoryMaps))
}
}
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 4,109 | AdventOfCode | MIT License |
src/main/kotlin/Day14.kt | SimonMarquis | 570,868,366 | false | {"Kotlin": 50263} | import kotlin.math.max
import kotlin.math.min
class Day14(input: List<String>) {
private val simulation = Simulation(input.walls())
fun part1(): Long = simulation.apply {
while (simulatePart1().not()) Unit
}.iterations.dec()
fun part2(): Long = simulation.apply {
while (simulatePart2().not()) Unit
}.iterations
private fun List<String>.walls() = flatMap {
it.split(" -> ").windowed(2, step = 1) { (src, dst) ->
val (srcX, srcY) = src.toPoint()
val (dstX, dstY) = dst.toPoint()
when {
srcX == dstX -> (min(srcY, dstY)..max(srcY, dstY)).map { y -> Point(srcX, y) }
srcY == dstY -> (min(srcX, dstX)..max(srcX, dstX)).map { x -> Point(x, srcY) }
else -> error(this)
}
}
}.flatten().toSet()
private fun String.toPoint() = split(",").map(String::toInt).let { (x, y) -> Point(x, y) }
private data class Point(val x: Int, val y: Int)
private class Simulation(walls: Set<Point>, private val source: Point = Point(500, 0)) {
private enum class Element { Sand, Wall }
private val data: MutableMap<Point, Element> = walls.foldInPlace(mutableMapOf()) { this[it] = Element.Wall }
private val limit = walls.maxBy { it.y }.y
var iterations = 0L
private set
private operator fun get(point: Point) = data[point]
/**
* @return `true` when sand starts flowing into the abyss, `false` when it settles.
*/
fun simulatePart1(): Boolean {
var point = source
iterations++
while (true) {
val new = point.step()
if (new == point) return false
if (new.y >= limit) return true
point = point becomes new
}
}
/**
* @return `true` when sand comes to rest at [source], `false` when it settles.
*/
fun simulatePart2(): Boolean {
var point = source
iterations++
while (true) {
val new = point.step()
if (new == source) return true
if (new == point || new.y >= limit + 2) return false
point = point becomes new
}
}
/**
* @return `this` if `this` [Point] is stable, a new [Point] otherwise
*/
private fun Point.step(): Point {
val down = copy(y = y + 1)
if (get(down) == null) return down
val downLeft = down.copy(x = down.x - 1)
if (get(downLeft) == null) return downLeft
val downRight = down.copy(x = down.x + 1)
if (get(downRight) == null) return downRight
return this
}
private infix fun Point.becomes(new: Point): Point = new.apply {
data.remove(this@becomes)
data[this] = Element.Sand
}
override fun toString(): String {
val minY = data.minOf { (it, _) -> it.y }.dec()
val maxY = data.maxOf { (it, _) -> it.y }.inc()
val minX = data.minOf { (it, _) -> it.x }.dec()
val maxX = data.maxOf { (it, _) -> it.x }.inc()
return (minY..maxY).joinToString("\n") { y ->
(minX..maxX).joinToString("") { x ->
when (get(Point(x, y))) {
Element.Sand -> "o"
Element.Wall -> "#"
null -> " "
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a2129cc558c610dfe338594d9f05df6501dff5e6 | 3,603 | advent-of-code-2022 | Apache License 2.0 |
src/main/aoc2020/Day1.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2020
class Day1(input: List<String>) {
// Most of the entries in the input will go past 2020 when summed
// so sort the list to start with smaller numbers to find the solution faster
private val entries = input.map { it.toInt() }.sorted()
fun solve(partOne: Boolean = false, partTwo: Boolean = false): Int {
// Keep a set of already seen numbers to save one for loop and reduce complexity
// from O(n^2) to O(n) in part 1 and O(n^3) to O(n^2) in part 2
val seen = mutableSetOf<Int>()
for (x in entries.indices) {
if (partOne) {
seen.add(entries[x])
val lookingFor = 2020 - entries[x]
if (seen.contains(lookingFor)) {
return entries[x] * lookingFor
}
}
if (partTwo) {
for (y in entries.indices) {
if (x != y) {
seen.add(entries[y])
val lookingFor = 2020 - entries[x] - entries[y]
if (seen.contains(lookingFor)) {
return entries[x] * entries[y] * lookingFor
}
}
}
}
}
return 0
}
fun solvePart1(): Int {
return solve(partOne = true)
}
fun solvePart2(): Int {
return solve(partTwo = true)
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,432 | aoc | MIT License |
src/Day11.kt | fmborghino | 573,233,162 | false | {"Kotlin": 60805} | // Monkey 0:
// Starting items: 79, 98
// Operation: new = old * 19
// Test: divisible by 23
// If true: throw to monkey 2
// If false: throw to monkey 3
// round is all monkeys act on all items
// each item ALSO gets divide by 3 and round down before action
// new items go to the end of the list
//
// count number times each monkey inspects an item
// result is product of two top inspectors
fun main() {
@Suppress("unused")
fun log(message: Any?) {
println(message)
}
class Operation(val op: Char, val value: Long?) // value = null when "old"
class Test(val op: Char = 'd', val value: Long, var trueMonkey: Int = 0, var falseMonkey: Int = 0)
class Monkey(var name: Int = 0, var inspections: Long = 0, var items: MutableList<Long>, val op: Operation?, val test: Test?)
// Monkey 0:
// Starting items: 79, 98
// Operation: new = old * 19 // also + N also * old (oddly not + old)
// Test: divisible by 23
// If true: throw to monkey 2
// If false: throw to monkey 3
fun parseMonkeys(input: List<String>): List<Monkey> {
val monkeys: MutableList<Monkey> = mutableListOf()
var mNumber: Int = 0
var items: MutableList<Long> = mutableListOf()
var op: Operation? = null
var test: Test? = null
// CONSIDER input.removeAll { it.isBlank() }.windowed(size = 6, step = 6).split("\n")
input.forEach { l ->
// log(l)
when {
// eh could just increment counter here... but hey what if part 2 is out of order?
l.startsWith("Monkey ") ->
mNumber = l.substringAfter(" ").substringBefore(":").toInt()
l.startsWith(" Starting items: ") ->
items = l.substringAfter(" Starting items: ").split(", ")
.map { it.toLong() }.toMutableList()
l.startsWith(" Operation: new = old ") -> {
val args = l.substringAfter(" Operation: new = old ").split(" ")
op = Operation(op = args[0][0], value = args[1].toLongOrNull())
}
l.startsWith(" Test: divisible by ") ->
test = Test(value = l.substringAfter(" Test: divisible by ").toLong())
l.startsWith(" If true:") -> test?.trueMonkey = l.split(" ").last().toInt()
l.startsWith(" If false:") -> test?.falseMonkey = l.split(" ").last().toInt()
l.isBlank() -> monkeys.add(Monkey(name = mNumber, items = items, op = op, test = test))
}
}
monkeys.add(Monkey(name = mNumber, items = items, op = op, test = test)) // last monkey
return monkeys
}
fun monkeyBusiness(monkey: Monkey, monkeys: List<Monkey>, part: Int = 1) {
monkey.items.forEach { item ->
val operand = monkey.op?.value ?: item // handles "old" which we stashed as Int? null
var newItem = (if (monkey.op?.op == '*') (item * operand) else (item + operand))
if (part == 1) { newItem /= 3 }
else {
val mod: Long = monkeys.map { it.test?.value!! }.reduce(Long::times)
newItem %= mod
}
if (newItem % monkey.test?.value!! == 0L) {
monkeys[monkey.test?.trueMonkey!!].items.add(newItem)
log("monkey ${monkey.name}: $item -> $newItem to true ${monkey.test?.trueMonkey!!}")
} else {
monkeys[monkey.test?.falseMonkey!!].items.add(newItem)
log("monkey ${monkey.name}: $item -> $newItem to false ${monkey.test?.falseMonkey!!}")
}
}
monkey.inspections += monkey.items.size
monkey.items = mutableListOf()
return
}
fun part1(input: List<String>): Long {
val monkeys: List<Monkey> = parseMonkeys(input)
log("STARTING\n${monkeys.map { it.items.joinToString(", ") }.joinToString("\n")}")
repeat(20) { round ->
monkeys.forEach { monkey ->
monkeyBusiness(monkey, monkeys)
}
log("AFTER ROUND ${round + 1}\n${monkeys.map { it.items.joinToString(", ") }.joinToString("\n")}")
}
return monkeys.map { it.inspections }.sortedDescending().take(2).fold(1) { a, v -> a * v }
}
fun part2(input: List<String>): Long {
val monkeys: List<Monkey> = parseMonkeys(input)
// log("STARTING\n${monkeys.map { it.items.joinToString(", ") }.joinToString("\n")}")
repeat(10_000) { round ->
monkeys.forEach { monkey ->
monkeyBusiness(monkey, monkeys, part = 2)
}
// log("AFTER ROUND ${round + 1}\n${monkeys.map { it.items.joinToString(", ") }.joinToString("\n")}")
}
return monkeys.map { it.inspections }.sortedDescending().take(2).fold(1) { a, v -> a * v }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day11_test.txt")
check(part1(testInput) == 10605L)
check(part2(testInput) == 2713310158L)
val input = readInput("Day11.txt")
println(part1(input))
check(part1(input) == 61503L)
println(part2(input))
check(part2(input) == 14081365540L)
}
| 0 | Kotlin | 0 | 0 | 893cab0651ca0bb3bc8108ec31974654600d2bf1 | 5,263 | aoc2022 | Apache License 2.0 |
src/Day03.kt | Hotkeyyy | 573,026,685 | false | {"Kotlin": 7830} | import java.io.File
fun main() {
val lowerCase = ('a'..'z').toList()
val upperCase = ('A'..'Z').toList()
fun part1(input: String) {
var result = 0
input.split("\r").map { it.trim() }.forEach {
val firstCompartment = it.substring(0, it.length / 2)
val secondCompartment = it.substring(it.length / 2, it.length)
var sameCharacter = ' '
secondCompartment.forEach { c -> if (firstCompartment.contains(c)) sameCharacter = c }
if (lowerCase.contains(sameCharacter)) result += (lowerCase.indexOf(sameCharacter) + 1)
if (upperCase.contains(sameCharacter)) result += (upperCase.indexOf(sameCharacter) + 27)
}
println(result)
}
fun part2(input: String) {
var result = 0
input.split("\r").map { it.trim() }.chunked(3).forEach { list ->
var sameCharacter = ' '
list.first().forEach { c ->
var lastContains = true
list.forEach {
if (lastContains && !it.contains(c)) lastContains = false
}
if (lastContains) sameCharacter = c
}
if (lowerCase.contains(sameCharacter)) result += (lowerCase.indexOf(sameCharacter) + 1)
if (upperCase.contains(sameCharacter)) result += (upperCase.indexOf(sameCharacter) + 27)
}
println(result)
}
val input = File("src/Day03.txt").readText()
part1(input)
part2(input)
} | 0 | Kotlin | 0 | 0 | dfb20f1254127f99bc845e9e13631c53de8784f2 | 1,505 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/tree/bintree/LCS.kt | yx-z | 106,589,674 | false | null | package tree.bintree
import util.get
import util.prettyPrintTree
import util.set
import java.util.*
// given two binary trees A and B, find a largest common subtree between them
// here we only care about their tree structure so no need to compare data
// return the root of this subtree in A
fun BinTreeNode<Int>.lst(B: BinTreeNode<Int>): BinTreeNode<Int> {
val A = this
val lvA = A.lvTrav() // level order traversal of A
// since data is irrelevant, we will override data as the index during the traversal
// o/w we can use a hashtable/build a separate tree for just storing indices
val m = lvA.size // # of nodes of A
// similarly for B
val lvB = B.lvTrav()
val n = lvB.size
// dp(i, j): # of nodes of lcs rooted @ lvA[i] and lvB[j]
// memoization structure: 2d arr dp[0 until m, 0 until n]
val dp = Array(m) { Array(n) { 0 } }
// space: O(mn)
// dp(i, j) = 1 if lvA[i] is a leaf or lvB[j] is a leaf
// = 1 if lvA[i] does/does not have a left child but lvB[j] does not/does OR
// lvA[i] does/does not have a right child but lvB[j] does not/does
// = 1 + dp(p, q) if both lvA[i] and lvB[j] only have a left/right child
// where lvA[p], lvB[q] is the left/right child
// = 1 + dp(p, q) + dp(u, v) if both lvA[i] and lvB[j] have both children
// where lvA[p], lvA[u], lvB[q], lvB[v] are corresponding children
// dependency: since lvA, lvB are level order traversals, children of a node
// will always have a larger index than it has
// that is to say, dp(i, j) depends on dp(p, q) where p > i, q > j
// we will keep a maximum size and its corresponding index in A, i.e. i
var maxSize = -1
var maxI = -1
// eval order: outer loop for i decreasing from m - 1 down to 0
for (i in m - 1 downTo 0) {
// inner loop for j decreasing from n - 1 down to 0
for (j in n - 1 downTo 0) {
dp[i, j] = when {
lvA[i].isLeaf() || lvB[j].isLeaf() -> 1
(lvA[i].left == null && lvB[j].left != null) ||
(lvA[i].left != null && lvB[j].left == null) ||
(lvA[i].right == null && lvB[j].right != null) ||
(lvA[i].right != null && lvB[j].right == null) -> 1
lvA[i].left != null && lvA[i].right == null && lvB[i].left != null && lvB[j].right == null -> 1 + dp[lvA[i].left!!.data, lvB[j].left!!.data]
lvA[i].left == null && lvA[i].right != null && lvB[j].left == null && lvB[j].right != null -> 1 + dp[lvA[i].right!!.data, lvB[j].right!!.data]
else -> // both children are non-null for lvA[i] and lvB[j]
1 + dp[lvA[i].left!!.data, lvB[j].left!!.data] + dp[lvA[i].right!!.data, lvB[j].right!!.data]
}
if (dp[i, j] > maxSize) {
maxSize = dp[i, j]
maxI = i
}
}
}
return lvA[maxI]
}
private fun BinTreeNode<Int>.lvTrav(): ArrayList<BinTreeNode<Int>> {
var index = 0
val lvTrav = ArrayList<BinTreeNode<Int>>()
val queue: Queue<BinTreeNode<Int>> = LinkedList<BinTreeNode<Int>>()
queue.add(this)
while (queue.isNotEmpty()) {
val node = queue.remove()
node.data = index
index++
lvTrav.add(node)
node.left?.run { queue.add(this) }
node.right?.run { queue.add(this) }
}
return lvTrav
}
private fun <T> BinTreeNode<T>.isLeaf() = left == null && right == null
fun main(args: Array<String>) {
val A = BinTreeNode(0)
A.left = BinTreeNode(0)
A.right = BinTreeNode(0)
A.left!!.left = BinTreeNode(0)
A.left!!.right = BinTreeNode(0)
A.right!!.left = BinTreeNode(0)
A.left!!.left!!.left = BinTreeNode(0)
A.left!!.left!!.right = BinTreeNode(0)
// A.prettyPrintTree()
val B = BinTreeNode(0)
B.left = BinTreeNode(0)
B.right = BinTreeNode(0)
B.right!!.left = BinTreeNode(0)
B.right!!.right = BinTreeNode(0)
B.right!!.left!!.left = BinTreeNode(0)
B.right!!.left!!.right = BinTreeNode(0)
B.right!!.left!!.left!!.left = BinTreeNode(0)
B.right!!.right!!.left = BinTreeNode(0)
B.right!!.right!!.right = BinTreeNode(0)
B.right!!.right!!.left!!.left = BinTreeNode(0)
B.right!!.right!!.left!!.right = BinTreeNode(0)
// B.prettyPrintTree()
(A.lst(B)).prettyPrintTree()
} | 0 | Kotlin | 0 | 1 | 15494d3dba5e5aa825ffa760107d60c297fb5206 | 4,048 | AlgoKt | MIT License |
2022/Day22/problems.kt | moozzyk | 317,429,068 | false | {"Rust": 102403, "C++": 88189, "Python": 75787, "Kotlin": 72672, "OCaml": 60373, "Haskell": 53307, "JavaScript": 51984, "Go": 49768, "Scala": 46794} | import java.io.File
enum class Direction {
RIGHT,
DOWN,
LEFT,
UP
}
fun main(args: Array<String>) {
val lines = File(args[0]).readLines()
var map = createMap(lines)
var path = getPath(lines)
println(problem1(map, path))
println(problem2(map, path))
}
fun createMap(lines: List<String>): List<CharArray> {
var map = lines.takeWhile { it != "" }
var maxWidth = map.map { it.length }.max()
return map.map { it + " ".repeat(maxWidth - it.length) }.map { it.toCharArray() }.toList()
}
fun getPath(lines: List<String>): String {
return lines.dropWhile { it != "" }[1]
}
fun problem1(map: List<CharArray>, path: String): Int {
var row = 0
var col = map[0].indexOf('.')
var direction = Direction.RIGHT
var pathIdx = 0
while (pathIdx < path.length) {
var steps = 0
do {
steps *= 10
steps += path[pathIdx].toString().toInt()
pathIdx++
} while (pathIdx < path.length && path[pathIdx].isDigit())
for (i in 0 until steps) {
var nextRow = row
var nextCol = col
if (direction == Direction.UP) {
nextRow--
if (nextRow < 0 || map[nextRow][nextCol] == ' ') {
nextRow = map.size - 1
while (map[nextRow][nextCol] == ' ') {
nextRow--
}
}
} else if (direction == Direction.DOWN) {
nextRow++
if (nextRow == map.size || map[nextRow][nextCol] == ' ') {
nextRow = 0
while (map[nextRow][nextCol] == ' ') {
nextRow++
}
}
} else if (direction == Direction.LEFT) {
nextCol--
if (nextCol < 0 || map[nextRow][nextCol] == ' ') {
nextCol = map[nextRow].size - 1
while (map[nextRow][nextCol] == ' ') {
nextCol--
}
}
} else if (direction == Direction.RIGHT) {
nextCol++
if (nextCol == map[nextRow].size || map[nextRow][nextCol] == ' ') {
nextCol = 0
while (map[nextRow][nextCol] == ' ') {
nextCol++
}
}
}
if (map[nextRow][nextCol] == '#') {
break
}
row = nextRow
col = nextCol
}
if (pathIdx < path.length) {
direction =
if (path[pathIdx] == 'L') {
Direction.values()[(4 + direction.ordinal - 1) % 4]
} else {
Direction.values()[(direction.ordinal + 1) % 4]
}
pathIdx++
}
}
return (row + 1) * 1000 + (col + 1) * 4 + direction.ordinal
}
fun problem2(map: List<CharArray>, path: String): Int {
var dir = 0
var pathIdx = 0
var row = 0
var col = map[0].indexOf('.')
while (pathIdx < path.length) {
var steps = 0
do {
steps *= 10
steps += path[pathIdx].toString().toInt()
pathIdx++
} while (pathIdx < path.length && path[pathIdx].isDigit())
for (i in 0 until steps) {
val (nextRow, nextCol, nextDir) = nextMove(row, col, dir)
if (map[nextRow][nextCol] == '.') {
row = nextRow
col = nextCol
dir = nextDir
} else if (map[nextRow][nextCol] != '#') {
throw Exception("Invalid position")
}
}
if (pathIdx < path.length) {
dir = (4 + dir + (if (path[pathIdx] == 'L') -1 else 1)) % 4
pathIdx++
}
}
return (row + 1) * 1000 + (col + 1) * 4 + dir
}
fun nextMove(row: Int, col: Int, dir: Int): Triple<Int, Int, Int> {
val sideSize = 50
val dRow = listOf(0, 1, 0, -1)
val dCol = listOf(1, 0, -1, 0)
val nextRow = row + dRow[dir]
val nextCol = col + dCol[dir]
val currSector = Pair(row / sideSize, col / sideSize)
val nextSector = Pair(nextRow.floorDiv(sideSize), nextCol.floorDiv(sideSize))
val sideRow = row % sideSize
val sideCol = col % sideSize
if (currSector == Pair(0, 1)) {
if (nextSector == Pair(-1, 1)) {
return Triple(3 * sideSize + sideCol, 0, Direction.RIGHT.ordinal)
}
if (nextSector == Pair(0, 0)) {
return Triple(3 * sideSize - 1 - sideRow, 0, Direction.RIGHT.ordinal)
}
}
if (currSector == Pair(0, 2)) {
if (nextSector == Pair(-1, 2)) {
return Triple(4 * sideSize - 1, sideCol, Direction.UP.ordinal)
}
if (nextSector == Pair(0, 3)) {
return Triple((3 * sideSize - 1) - sideRow, 2 * sideSize - 1, Direction.LEFT.ordinal)
}
if (nextSector == Pair(1, 2)) {
return Triple(sideSize + sideCol, 2 * sideSize - 1, Direction.LEFT.ordinal)
}
}
if (currSector == Pair(1, 1)) {
if (nextSector == Pair(1, 0)) {
return Triple(2 * sideSize, sideRow, Direction.DOWN.ordinal)
}
if (nextSector == Pair(1, 2)) {
return Triple(sideSize - 1, (2 * sideSize) + sideRow, Direction.UP.ordinal)
}
}
if (currSector == Pair(2, 0)) {
if (nextSector == Pair(1, 0)) {
return Triple(sideSize + sideCol, sideSize, Direction.RIGHT.ordinal)
}
if (nextSector == Pair(2, -1)) {
return Triple(sideSize - 1 - sideRow, sideSize, Direction.RIGHT.ordinal)
}
}
if (currSector == Pair(2, 1)) {
if (nextSector == Pair(2, 2)) {
return Triple(sideSize - 1 - sideRow, 3 * sideSize - 1, Direction.LEFT.ordinal)
}
if (nextSector == Pair(3, 1)) {
return Triple(3 * sideSize + sideCol, sideSize - 1, Direction.LEFT.ordinal)
}
}
if (currSector == Pair(3, 0)) {
if (nextSector == Pair(3, -1)) {
return Triple(0, sideSize + sideRow, Direction.DOWN.ordinal)
}
if (nextSector == Pair(3, 1)) {
return Triple(3 * sideSize - 1, sideSize + sideRow, Direction.UP.ordinal)
}
if (nextSector == Pair(4, 0)) {
return Triple(0, 2 * sideSize + sideCol, Direction.DOWN.ordinal)
}
}
return Triple(nextRow, nextCol, dir)
}
| 0 | Rust | 0 | 0 | c265f4c0bddb0357fe90b6a9e6abdc3bee59f585 | 6,546 | AdventOfCode | MIT License |
src/Day01.kt | Virendra115 | 573,122,699 | false | {"Kotlin": 2427} | import java.util.Collections.sort
import java.util.Comparator
fun main() {
fun part1(input: String): Int {
val list = input.split("\r\n\r\n").map { a -> a.split("\r\n").sumOf { it.toInt() } }
return list.max()
}
fun part2(input: String): Int {
val list = input.split("\r\n\r\n").map { a -> a.split("\r\n").sumOf { it.toInt() } }
sort(list, Comparator.reverseOrder())
return list[0] + list[1] + list[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 44aff316ffe08d27d23f2f2d8ce7d027a0e64ff8 | 707 | AdventOfCode-in-kotlin | Apache License 2.0 |
src/main/kotlin/com/sk/set0/77. Combinations.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set0
class Solution77 {
fun combine(n: Int, k: Int): List<List<Int>> {
val result = ArrayList<ArrayList<Int>>()
combine(1, n, k, ArrayList(), result)
return result
}
private fun combine(start: Int, end: Int, k: Int, list: ArrayList<Int>, result: ArrayList<ArrayList<Int>>) {
if (k == 0) {
result.add(list)
return
}
for (i in start..end) {
val list = ArrayList(list) // make fresh copy of list
list.add(i)
combine(i + 1, end, k - 1, list, result)
}
}
fun combine2(n: Int, k: Int): List<List<Int>> {
val result: MutableList<List<Int>> = ArrayList()
var i = 0
val arr = IntArray(k)
while (i >= 0) {
arr[i]++
if (arr[i] > n) {
i--
} else if (i == k - 1) {
val combination = ArrayList<Int>()
for (num in arr) {
combination.add(num)
}
result.add(combination)
} else {
i++
arr[i] = arr[i - 1]
}
}
return result
}
// https://leetcode.com/problems/combinations/solutions/26992/short-iterative-c-answer-8ms/?envType=study-plan-v2&envId=top-interview-150
fun combine3(n: Int, k: Int): List<List<Int>> {
val result: MutableList<List<Int>> = ArrayList()
var i = 0
val arr = IntArray(k)
val list = ArrayList<Int>()
while (i >= 0) {
arr[i]++
list.add(arr[i])
if (arr[i] > n) {
i--
list.removeLast()
if (list.isNotEmpty()) list.removeLast()
} else if (i == k - 1) {
result.add(ArrayList(list))
list.removeLast()
} else {
i++
arr[i] = arr[i - 1]
}
}
return result
}
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 2,003 | leetcode-kotlin | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day02.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 2 - Dive!
* Problem Description: http://adventofcode.com/2021/day/2
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day2/
*/
package com.ginsberg.advent2021
class Day02(input: List<String>) {
private val commands = input.map { Command.of(it) }
fun solvePart1(): Int =
commands.fold(Submarine()) { submarine, command -> submarine.movePart1(command) }.answer()
fun solvePart2(): Int =
commands.fold(Submarine()) { submarine, command -> submarine.movePart2(command) }.answer()
private data class Submarine(val depth: Int = 0, val position: Int = 0, val aim: Int = 0) {
fun answer() = depth * position
fun movePart1(command: Command): Submarine =
when (command.name) {
"forward" -> copy(position = position + command.amount)
"down" -> copy(depth = depth + command.amount)
"up" -> copy(depth = depth - command.amount)
else -> error("Invalid command")
}
fun movePart2(command: Command) =
when (command.name) {
"forward" -> copy(
position = position + command.amount,
depth = depth + (aim * command.amount)
)
"down" -> copy(aim = aim + command.amount)
"up" -> copy(aim = aim - command.amount)
else -> error("Invalid command")
}
}
private class Command(val name: String, val amount: Int) {
companion object {
fun of(input: String) = input.split(" ").let { Command(it.first(), it.last().toInt()) }
}
}
} | 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 1,739 | advent-2021-kotlin | Apache License 2.0 |
codeforces/round572/c.kt | mikhail-dvorkin | 93,438,157 | false | {"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408} | package codeforces.round572
private const val M = 998244353
private fun solve() {
val (n, m) = readInts()
val a = readInts().sorted()
val maxDiff = (a.last() - a.first()) / (m - 1)
val d = Array(m) { IntArray(n + 1) }
var ans = 0
for (diff in 1..maxDiff) {
var iPrev = 0
for (i in a.indices) {
while (a[i] - a[iPrev] >= diff) iPrev++
d[0][i + 1] = i + 1
for (j in 1 until m) {
d[j][i + 1] = (d[j][i] + d[j - 1][iPrev]) % M
}
}
ans = (ans + d[m - 1][n]) % M
}
println(ans)
}
fun main() {
val stdStreams = (false to true)
val isOnlineJudge = System.getProperty("ONLINE_JUDGE") == "true"
if (!isOnlineJudge) {
if (!stdStreams.first) System.setIn(java.io.File("input.txt").inputStream())
if (!stdStreams.second) System.setOut(java.io.PrintStream("output.txt"))
}
val tests = if (isOnlineJudge) 1 else readInt()
repeat(tests) { solve() }
}
private fun readLn() = readLine()!!
private fun readInt() = readLn().toInt()
private fun readStrings() = readLn().split(" ")
private fun readInts() = readStrings().map { it.toInt() }
| 0 | Java | 1 | 9 | 30953122834fcaee817fe21fb108a374946f8c7c | 1,064 | competitions | The Unlicense |
solutions/src/solutions/y20/day 20.kt | Kroppeb | 225,582,260 | false | null | @file:Suppress("PackageDirectoryMismatch")
package solutions.y20.d20
import grid.Clock
import helpers.*
val xxxxx = Clock(6, 3);
private fun part1(data: Data) {
val tiles = data.splitOn { it.isBlank() }.filter { it.isNotEmpty() }.map {
val id = it.first().getInt()
val shape = it.drop(1)
id to shape
}.toMap()
val edges = tiles.flatMap { (id, tile) ->
listOf(
tile.first(),
tile.last(),
tile.map { it.first() }.joinToString(separator = ""),
tile.map { it.last() }.joinToString(separator = "")).map {
val r = it.reversed()
if (r < it)
r
else it
}.map { it to id }
}.groupBy { it.first }.filter { it.value.size == 1 }.flatMap { it.value }.map { it.second!!.toLong() }
.groupBy { it }.filter { it.value.size == 2 }.map { it.value[0] }.toSet().log().reduce { a, b -> a * b }.log()
}
private fun part2(data: Data) {
val tiles = data.splitOn { it.isBlank() }.filter { it.isNotEmpty() }.map {
val id = it.first().getInt()!!
val shape = it.drop(1)
id to shape
}.toMap()
val edges = tiles.flatMap { (id, tile) ->
listOf(
tile.first(),
tile.last(),
tile.map { it.first() }.joinToString(separator = ""),
tile.map { it.last() }.joinToString(separator = "")).map {
val r = it.reversed()
if (r < it)
r
else it
}.map { it to id }
}.groupBy { it.first }
val sds = edges
.flatMap { it.value.map { it.second to it.first } }
.groupBy { it.first }
.mapValues { it.value.map { it.second } }
val corners = edges.filter { it.value.size == 1 }.flatMap { it.value }.map { it.second!! }
.groupBy { it }.filter { it.value.size == 2 }.map { it.value[0] }
val sides = edges.filter { it.value.size == 1 }.flatMap { it.value }.map { it.second!! }
.groupBy { it }.filter { it.value.size == 1 }.map { it.value[0] }.toSet()
val size = sides.size / 4 + 2
val grid = MutableList(size) { MutableList(size) { null as Int? } }
grid[0][0] = corners[0]
var cur = corners[0]
var used = mutableSetOf<Int>(cur)
for (i in 1 until (size - 1)) {
cur = sds[cur]!!.flatMap { edges[it]!!.map { it.second } }.first { it in sides && it !in used }
grid[0][i] = cur
used.add(cur)
}
cur = sds[cur]!!.flatMap { edges[it]!!.map { it.second } }.first { it in corners && it !in used }
grid[0][size - 1] = cur
used.add(cur)
for (x in 1 until (size - 1)) {
cur = sds[grid[x - 1][0]]!!.flatMap { edges[it]!!.map { it.second } }.first { it in sides && it !in used }
grid[x][0] = cur
used.add(cur)
for (i in 1 until (size - 1)) {
cur = sds[grid[x - 1][i]]!!.flatMap { edges[it]!!.map { it.second } }.first { it !in sides && it !in used }
grid[x][i] = cur
used.add(cur)
}
cur = sds[grid[x - 1][size - 1]]!!
.flatMap { edges[it]!!.map { it.second } }.first { it in sides && it !in used }
grid[x][size - 1] = cur
used.add(cur)
}
cur = sds[grid[size - 2][0]]!!.flatMap { edges[it]!!.map { it.second } }.first { it in corners && it !in used }
grid[size - 1][0] = cur
used.add(cur)
for (i in 1 until (size - 1)) {
cur = sds[cur]!!.flatMap { edges[it]!!.map { it.second } }.first { it in sides && it !in used }
grid[size - 1][i] = cur
used.add(cur)
}
cur = sds[cur]!!.flatMap { edges[it]!!.map { it.second } }.first { it in corners && it !in used }
grid[size - 1][size - 1] = cur
used.add(cur)
grid as List<List<Int>>
println(grid.map { it.joinToString(postfix = "\n") })
val rot = MutableList(size) { MutableList(size) { null as List<List<Char>>? } }
var a = grid[0][0]
var b = grid[0][1]
val edg = sds[a]!!.intersect(sds[b]!!).first()
val ag = tiles[a]!!.e()
val at = List(ag[0].size){i -> ag.map{it[i]}}
rot[0][0] = when (edg.e()) {
ag.map { it.last() } -> ag
ag.map { it.last() }.reversed() -> ag.reversed()
ag.map { it.first() } -> ag.map { it.reversed() }
ag.map { it.first() }.reversed() -> ag.reversed().map { it.reversed() }
at.map { it.last() } -> at
at.map { it.last() }.reversed() -> at.reversed()
at.map { it.first() } -> at.map { it.reversed() }
at.map { it.first() }.reversed() -> at.reversed().map { it.reversed() }
else -> error("")
}
// add/ remove revesed manually
if(edges[rot[0][0]!!.last().joinToString(separator = "").reversed()]!!.size == 1){
rot[0][0] = rot[0][0]!!.reversed()
}
for(i in 1 until size){
val edg = rot[i - 1][0]!!.last()
val a = grid[i][0]
val ag = tiles[a]!!.e()
val at = List(ag[0].size){i -> ag.map{it[i]}}
//println(edg)
rot[i][0] = when (edg) {
ag.first() -> ag
ag.first().reversed() -> ag.map { it.reversed() }
ag.last() -> ag.reversed()
ag.last().reversed() -> ag.reversed().map { it.reversed() }
at.first() -> at
at.first().reversed() -> at.map { it.reversed() }
at.last() -> at.reversed()
at.last().reversed() -> at.reversed().map { it.reversed() }
else -> error("")
}
}
for(i in 1 until size){
for(j in 0 until size) {
//println("$i,$j")
val edg = rot[j][i-1]!!.map{it.last()}
val a = grid[j][i]
val ag = tiles[a]!!.e()
val at = List(ag[0].size) { i -> ag.map { it[i] } }
//println(edg)
rot[j][i] = when (edg) {
ag.map { it.first() } -> ag
ag.map { it.first() }.reversed() -> ag.reversed()
ag.map { it.last() } -> ag.map { it.reversed() }
ag.map { it.last() }.reversed() -> ag.reversed().map { it.reversed() }
at.map { it.first() } -> at
at.map { it.first() }.reversed() -> at.reversed()
at.map { it.last() } -> at.map { it.reversed() }
at.map { it.last() }.reversed() -> at.reversed().map { it.reversed() }
else -> error("")
}
}
}
val p = rot.map{l->l.map{it!!.drop(1).dropLast(1).map{it.drop(1).dropLast(1)}}}
val mg = List(p.size * p[0][0].size){i ->
val a = i / p[0][0].size
val b = i % p[0][0].size
p[a].flatMap { it[b] }
}
val mt = List(mg[0].size) { i -> mg.map { it[i] } }
val monster = listOf(
" # ",
"# ## ## ###",
" # # # # # # ")
val ms = listOf(mg,mt).flatMap { listOf(it, it.reversed()) }.flatMap { listOf(it, it.map{it.reversed()}) }
val m = ms[4] // gotta do this yourself
//val m = monster.e()
val mr = monster.map{it.e().map{
if(it == ' ') "." else "(#|O)"
}.joinToString(separator = "")}.joinToString(separator = ".".repeat(m[0].size - monster[0].length)).let{Regex(it)}
println(m.map { it.joinToString(postfix = "\n",separator = "") })
var u = m.map { it.joinToString(separator = "")}.joinToString(separator = "")
println(mr.pattern)
var uu = u
do {
u = uu
uu = mr.replace(u){
//println(it.value)
it.value.mapIndexed { index: Int, c: Char ->
val line = index / m[0].size
val i = index % m[0].size
//println("$line:$i")
if(i >= monster[0].length)
c
else{
val k = monster[line][i]
if(k == '#')
'O'
else
c
}
}.joinToString(separator = "")
}
println("O: ${uu.count{it == 'O'}}")
println("#: ${uu.count{it == '#'}}")
} while(uu != u)
val rrr = Regex("\\(#\\|O\\)")
for( i in 0..14) {
var ii = 0
val mrr = Regex(rrr.replace(mr.pattern){
if(ii++ == i){
"#"
} else it.value
})
do {
u = uu
uu = mrr.replace(u) {
//println(it.value)
it.value.mapIndexed { index: Int, c: Char ->
val line = index / m[0].size
val i = index % m[0].size
//println("$line:$i")
if (i >= monster[0].length)
c
else {
val k = monster[line][i]
if (k == '#')
'O'
else
c
}
}.joinToString(separator = "")
}
println("O: ${uu.count { it == 'O' }}")
println("#: ${uu.count { it == '#' }}")
} while (uu != u)
}
//println(uu.chunked(m[0].size).joinToString(separator = "\n"))
println("O: ${uu.count{it == 'O'}}")
println("#: ${uu.count{it == '#'}}")
}
private typealias Data = Lines
fun main() {
val data: Data = getLines(2020_20)
part1(data)
part2(data)
}
fun <T> T.log(): T = also { println(this) } | 0 | Kotlin | 0 | 1 | 744b02b4acd5c6799654be998a98c9baeaa25a79 | 7,883 | AdventOfCodeSolutions | MIT License |
src/main/java/com/barneyb/aoc/aoc2022/day04/CampCleanup.kt | barneyb | 553,291,150 | false | {"Kotlin": 184395, "Java": 104225, "HTML": 6307, "JavaScript": 5601, "Shell": 3219, "CSS": 1020} | package com.barneyb.aoc.aoc2022.day04
import com.barneyb.aoc.util.*
fun main() {
Solver.execute(
::parse,
::countContained,
::countOverlapping
)
}
typealias Assignment = IntRange
typealias PairsOfAssignments = List<Pair<Assignment, Assignment>>
fun countContained(pairs: PairsOfAssignments) =
pairs.count { (a, b) ->
a.fullyContains(b) || b.fullyContains(a)
}
fun countOverlapping(pairs: PairsOfAssignments) =
pairs.count { (a, b) ->
a.overlaps(b)
}
internal fun parse(input: String) =
input.toSlice()
.trim()
.lines()
.map(::parsePair)
internal fun parsePair(str: CharSequence) =
//2-3,4-5
str.indexOf(',').let { idx ->
Pair(
parseAssignment(str.subSequence(0, idx)),
parseAssignment(str.subSequence(idx + 1, str.length))
)
}
internal fun parseAssignment(str: CharSequence) =
//2-3
str.indexOf('-').let { idx ->
Assignment(
str.subSequence(0, idx).toInt(),
str.subSequence(idx + 1, str.length).toInt()
)
}
| 0 | Kotlin | 0 | 0 | 8b5956164ff0be79a27f68ef09a9e7171cc91995 | 1,111 | aoc-2022 | MIT License |
Retos/Reto #1 - EL LENGUAJE HACKER [Fácil]/kotlin/malopezrom.kts | mouredev | 581,049,695 | false | {"Python": 3866914, "JavaScript": 1514237, "Java": 1272062, "C#": 770734, "Kotlin": 533094, "TypeScript": 457043, "Rust": 356917, "PHP": 281430, "Go": 243918, "Jupyter Notebook": 221090, "Swift": 216751, "C": 210761, "C++": 164758, "Dart": 159755, "Ruby": 70259, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 30892, "Shell": 27625, "R": 19771, "Lua": 16625, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12715, "F#": 12710, "Pascal": 12673, "Haskell": 11051, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1342, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "NewLisp": 124, "Haxe": 112, "HolyC": 110, "GLSL": 106, "CWeb": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | import java.util.*
/*
* Escribe un programa que reciba un texto y transforme lenguaje natural a
* "lenguaje hacker" (conocido realmente como "leet" o "1337"). Este lenguaje
* se caracteriza por sustituir caracteres alfanuméricos.
* - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/)
* con el alfabeto y los números en "leet".
* (Usa la primera opción de cada transformación. Por ejemplo "4" para la "a")
*/
/**
* Translates a string to leet speak intermediate using a map
*/
fun leetSpeakTranslator(text: String):String {
val leetDictionary = mapOf(
"a" to "4",
"b" to "I3",
"c" to "[",
"d" to ")",
"e" to "3",
"f" to "|=",
"g" to "&",
"h" to "#",
"i" to "1",
"j" to ",_|",
"k" to ">|",
"l" to "1",
"m" to "/\\/\\",
"n" to "^/",
"o" to "0",
"p" to "|*",
"q" to "(_,)",
"r" to "I2",
"s" to "5",
"t" to "7",
"u" to "(_)",
"v" to "\\/",
"w" to "\\/\\/",
"x" to "><",
"y" to "j",
"z" to "2",
"0" to "o",
"1" to "L",
"2" to "R",
"3" to "E",
"4" to "A",
"5" to "S",
"6" to "b",
"7" to "T",
"8" to "B",
"9" to "g"
)
var hackerText = ""
text.forEach { char ->
val replaceChar = leetDictionary.getOrDefault(char.toString().lowercase(Locale.getDefault()), char.toString()).let {
hackerText += it
}
}
return hackerText
}
/**
* Test Cases
*/
println(leetSpeakTranslator("Feliz 2023!"))
println(leetSpeakTranslator("Yo soy la primavera que ha llegado\n" +
"con un ramillete de violetas,\n" +
"y soy el sol que ha salido hoy\n" +
"para iluminar tus ojos de gitana.\n" +
"\n" +
"Soy el aire que te envuelve\n" +
"y el agua que te baña,\n" +
"y soy el fuego que te quema\n" +
"en la hoguera del querer."))
| 4 | Python | 2,929 | 4,661 | adcec568ef7944fae3dcbb40c79dbfb8ef1f633c | 2,192 | retos-programacion-2023 | Apache License 2.0 |
modules/core/src/main/kotlin/datamaintain/core/step/sort/ByCaseInsensitiveSeparatorFreeAlphabeticalSortingStrategy.kt | fbreuneval | 341,502,205 | true | {"Kotlin": 121123, "JavaScript": 533} | package datamaintain.core.step.sort
import datamaintain.core.script.Script
/**
* Allow to sort scripts considering the parts of the value returned by the getter.
* The parts list is given by a split on all chars that are not a figure or a letter.
* The number parts would be sorted as number, and the others as string (so with alphabetical sort)
*
* We assume the differents values have an homogeneity. For instance, you will have troubles
* to sort ["abc.123", "abc.234", "abc.0001", "abc.def"]
*/
class ByCaseInsensitiveSeparatorFreeAlphabeticalSortingStrategy : SortingStrategy<String>() {
private val numberRegex = "^\\d*$".toRegex()
override fun <T : Script> sort(scripts: List<T>, getter: (T) -> String): List<T> {
return scripts.sortedWith(Comparator { script1, script2 ->
val value1 = split(getter(script1))
val value2 = split(getter(script2))
var compareResult = 0;
for ((index, part1) in value1.withIndex()) {
if (value2.size <= index) {
// value1 is after value2 because value1 has more parts than value2
compareResult = 1;
break
} else {
val part2 = value2.get(index)
val lengthComparison = part1.length.compareTo(part2.length)
if (lengthComparison != 0) {
// The length are not equals.
// When part are number, then we can simply sort them assuming their length
if (numberRegex.matches(part1)) {
// The part having the smallest size is before
compareResult = lengthComparison
break
}
}
val compareTo = part1.compareTo(part2)
if (compareTo != 0) {
// The 2 part are not equals so we know the order of the scripts
compareResult = compareTo;
break
}
}
}
if (compareResult == 0 && value1.size != value2.size) {
// The last case is when value2 is longer than value1. It means value2 has more parts than value1,
// so value2 is after value1
compareResult = -1;
}
compareResult;
})
}
private fun split(value: String) = value.toLowerCase().split(Regex("[^0-9a-zA-Z]"))
}
| 0 | Kotlin | 0 | 0 | c1856e0ec9bc4fe54717c94a74e16b80a03d1319 | 2,572 | datamaintain | Apache License 2.0 |
src/main/kotlin/com/hj/leetcode/kotlin/problem985/Solution.kt | hj-core | 534,054,064 | false | {"Kotlin": 619841} | package com.hj.leetcode.kotlin.problem985
/**
* LeetCode page: [985. Sum of Even Numbers After Queries](https://leetcode.com/problems/sum-of-even-numbers-after-queries/);
*/
class Solution {
/* Complexity:
* Time O(N+M) and Aux_Space O(N) where N and M are the size of nums and queries;
*/
fun sumEvenAfterQueries(nums: IntArray, queries: Array<IntArray>): IntArray {
val ans = IntArray(queries.size)
var sumOfEven = getSumOfEven(nums)
val newNums = nums.clone()
for (index in queries.indices) {
val query = queries[index]
val numIndex = query[1]
if (newNums[numIndex].isEven()) sumOfEven -= newNums[numIndex]
newNums[numIndex] += query[0]
if (newNums[numIndex].isEven()) sumOfEven += newNums[numIndex]
ans[index] = sumOfEven
}
return ans
}
private fun getSumOfEven(nums: IntArray): Int {
var sum = 0
for (num in nums) {
if (num.isEven()) sum += num
}
return sum
}
private fun Int.isEven() = this and 1 == 0
} | 1 | Kotlin | 0 | 1 | 14c033f2bf43d1c4148633a222c133d76986029c | 1,113 | hj-leetcode-kotlin | Apache License 2.0 |
kotlin/src/com/daily/algothrim/leetcode/Connect.kt | idisfkj | 291,855,545 | false | null | package com.daily.algothrim.leetcode
import java.util.*
/**
* 116. 填充每个节点的下一个右侧节点指针
*
* 给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。
* 填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
*
* 初始状态下,所有next 指针都被设置为 NULL。
*/
class Connect {
companion object {
@JvmStatic
fun main(args: Array<String>) {
Connect().solution(Node(1,
Node(2,
Node(4), Node(5)),
Node(3,
Node(6), Node(7)
)
))?.let {
it.printMid(it)
}
println()
Connect().solutionV2(Node(1,
Node(2,
Node(4), Node(5)),
Node(3,
Node(6), Node(7)
)
))?.let {
it.printMid(it)
}
}
}
data class Node(var data: Int, var left: Node? = null, var right: Node? = null, var next: Node? = null) {
fun printMid(node: Node) {
node.left?.let { printMid(it) }
println(node.data)
println("next: ${node.next?.data}")
node.right?.let { printMid(it) }
}
}
/**
* 层次遍历
* O(n)
*/
fun solution(root: Node?): Node? {
if (root == null) return root
val deque = ArrayDeque<Node>()
val flag = Node(1)
deque.offer(root)
deque.offer(flag)
while (deque.isNotEmpty()) {
var pre: Node? = null
var item = deque.poll()
while (item != flag && item != null) {
item.left?.let {
deque.offer(it)
}
item.right?.let {
deque.offer(it)
}
pre?.next = item
pre = item
item = deque.poll()
}
if (deque.isNotEmpty()) deque.offer(flag)
}
return root
}
/**
* O(n)
*/
fun solutionV2(root: Node?): Node? {
if (root == null) return root
var mostLeft = root
while (mostLeft != null) {
var head = mostLeft
while (head != null) {
// 1 同父亲相邻节点
head.left?.next = head.right
// 2 不同父亲相邻节点
if (head.next != null) {
head.right?.next = head.next?.left
}
head = head.next
}
mostLeft = mostLeft.left
}
return root
}
} | 0 | Kotlin | 9 | 59 | 9de2b21d3bcd41cd03f0f7dd19136db93824a0fa | 2,874 | daily_algorithm | Apache License 2.0 |
src/Day06.kt | JCampbell8 | 572,669,444 | false | {"Kotlin": 10115} | fun main() {
fun String.allUnique(): Boolean = all(hashSetOf<Char>()::add)
fun detectPacketMarker(packet: String, distinct: Int): Int {
val marker = packet.toList().windowed(distinct, 1).first {
it.joinToString("").allUnique()
}
return packet.indexOf(marker.joinToString("")) + distinct
}
fun part1(input: List<String>): Int {
return detectPacketMarker(input[0], 4)
}
fun part2(input: List<String>): Int {
return detectPacketMarker(input[0], 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 1 | 0bac6b866e769d0ac6906456aefc58d4dd9688ad | 809 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/days/Day2.kt | sicruse | 434,002,213 | false | {"Kotlin": 29921} | package days
import kotlin.math.absoluteValue
class Day2 : Day(2) {
private val course: List<Instruction> by lazy { inputList.map { code -> Instruction.fromText(code) } }
data class Instruction(val maneuver: Maneuver, val amount: Int) {
companion object {
fun fromText(code: String): Instruction {
val instruction = code.split(" ")
val maneuver = instruction.first()
val amount = instruction.last().toInt()
return Instruction(Maneuver.valueOf(maneuver), amount)
}
}
}
data class Position(val horizontal: Int, val depth: Int)
data class PositionWithAim(val position: Position, val aim: Int)
enum class Maneuver {
forward {
override fun execute(from: Position, amount: Int): Position = Position(from.horizontal + amount, from.depth)
override fun execute(from: PositionWithAim, amount: Int): PositionWithAim {
val h = from.position.horizontal + amount
val d = from.position.depth + from.aim * amount
return PositionWithAim(Position(h, d), from.aim)
}
},
down {
override fun execute(from: Position, amount: Int): Position = Position(from.horizontal, from.depth + amount)
override fun execute(from: PositionWithAim, amount: Int): PositionWithAim =
PositionWithAim(from.position, from.aim + amount)
},
up {
override fun execute(from: Position, amount: Int): Position = Position(from.horizontal, from.depth - amount)
override fun execute(from: PositionWithAim, amount: Int): PositionWithAim =
PositionWithAim(from.position, from.aim - amount)
};
abstract fun execute(from: Position, amount: Int): Position
abstract fun execute(from: PositionWithAim, amount: Int): PositionWithAim
}
private fun navigate(course: List<Instruction>): Sequence<Position> = sequence {
var currentPosition = Position(0, 0)
for (instruction in course) {
val newPosition = instruction.maneuver.execute(currentPosition, instruction.amount)
currentPosition = newPosition
yield(newPosition)
}
}
private fun navigateWithAim(course: List<Instruction>): Sequence<PositionWithAim> = sequence {
var currentPosition = PositionWithAim(Position(0, 0), 0)
for (instruction in course) {
val newPosition = instruction.maneuver.execute(currentPosition, instruction.amount)
currentPosition = newPosition
yield(newPosition)
}
}
override fun partOne(): Any {
val finalPosition = navigate(course).last()
return finalPosition.horizontal.absoluteValue * finalPosition.depth.absoluteValue
}
override fun partTwo(): Any {
val finalPosition = navigateWithAim(course).last()
return finalPosition.position.horizontal.absoluteValue * finalPosition.position.depth.absoluteValue
}
}
| 0 | Kotlin | 0 | 0 | 172babe6ee67a86a7893f8c9c381c5ce8e61908e | 3,077 | aoc-kotlin-2021 | Creative Commons Zero v1.0 Universal |
src/main/kotlin/Utils.kt | brigham | 573,127,412 | false | {"Kotlin": 59675} | import java.io.File
import java.util.*
import kotlin.collections.ArrayDeque
/**
* Reads lines from the given input txt file.
*/
fun readInput(name: String) = File("src/main/kotlin", "$name.txt")
.also { it.createNewFile() }
.readLines()
fun slurp(name: String): String = File("src/main/kotlin", "$name.txt")
.also { it.createNewFile() }
.readText()
fun <E> Sequence<E>.chunkedBy(predicate: (E) -> Boolean): Sequence<List<E>> {
val outer = this
var justYielded = false
return sequence {
val list = mutableListOf<E>()
for (item in outer) {
justYielded = false
if (predicate(item)) {
list.add(item)
} else {
yield(list.toList())
list.clear()
justYielded = true
}
}
if (!justYielded) {
yield(list.toList())
}
}
}
fun <E : Comparable<E>> heap(): PriorityQueue<E> {
return PriorityQueue<E>()
}
fun <E : Comparable<E>> descendingHeap(): PriorityQueue<E> {
return heap(naturalOrder<E>().reversed())
}
fun <E> heap(comparator: Comparator<E>): PriorityQueue<E> {
return PriorityQueue<E>(comparator)
}
fun <E : Comparable<E>> min(a: E, b: E): E {
return if (a < b) a else b
}
fun <E : Comparable<E>> max(a: E, b: E): E {
return if (a > b) a else b
}
fun IntRange.overlap(other: IntRange): IntRange? {
if (endInclusive < other.first || other.last < start) {
return null
}
return max(start, other.first)..min(endInclusive, other.last)
}
fun <T, R> Pair<T, T>.map(transform: (T) -> R): Pair<R, R> =
transform(first) to transform(second)
// Graphs
data class GraphNode<N>(val steps: Int, val value: N)
fun <N> bfs(vararg start: N, next: (N) -> Sequence<N>, found: (N) -> Boolean): GraphNode<N>? {
val q = ArrayDeque<GraphNode<N>>()
val seen = mutableSetOf<N>()
q.addAll(start.map { GraphNode(0, it) })
while (q.isNotEmpty()) {
val nextNode = q.removeFirst()
if (nextNode.value in seen) {
continue
}
seen.add(nextNode.value)
if (found(nextNode.value)) {
return nextNode
}
for (it in next(nextNode.value)) {
q.add(GraphNode(nextNode.steps + 1, it))
}
}
return null
} | 0 | Kotlin | 0 | 0 | b87ffc772e5bd9fd721d552913cf79c575062f19 | 2,327 | advent-of-code-2022 | Apache License 2.0 |
src/main/kotlin/adventofcode2022/solution/day_11.kt | dangerground | 579,293,233 | false | {"Kotlin": 51472} | package adventofcode2022.solution
import adventofcode2022.util.readDay
import java.lang.Long.max
fun main() {
Day11("11").solve()
}
class Day11(private val num: String) {
private val inputText = readDay(num)
fun solve() {
println("Day $num Solution")
println("* Part 1: ${solution1()}")
println("* Part 2: ${solution2()}")
}
fun solution1(): Long {
val monkeys = realMonkey()
val monkeyCount = mutableMapOf<Int, Long>()
repeat(20) {
monkeys.forEach { x ->
val monkey = x.value
monkeyCount[x.key] = (monkeyCount[x.key] ?: 0) + monkey.items.size
monkey.items
.map { monkey.operation(it) }
.map { it / 3 }
.forEach {
val target = if (it % monkey.test == 0L) monkey.ifTrue else monkey.ifFalse
monkeys[target]!!.items.add(it)
}
monkey.items.clear()
}
}
monkeys.forEach {
println("Monkey ${it.key} -> ${it.value.items}")
}
val best = monkeyCount.map { it.value }.sortedDescending().take(2)
return best[0] * best[1]
}
private fun realMonkey() = mapOf(
0 to Monkey(
items = mutableListOf(57, 58),
operation = { it * 19 },
test = 7,
ifTrue = 2,
ifFalse = 3,
),
1 to Monkey(
items = mutableListOf(66, 52, 59, 79, 94, 73),
operation = { it + 1 },
test = 19,
ifTrue = 4,
ifFalse = 6,
),
2 to Monkey(
items = mutableListOf(80),
operation = { it + 6 },
test = 5,
ifTrue = 7,
ifFalse = 5,
),
3 to Monkey(
items = mutableListOf(82, 81, 68, 66, 71, 83, 75, 97),
operation = { it + 5 },
test = 11,
ifTrue = 5,
ifFalse = 2,
),
4 to Monkey(
items = mutableListOf(55, 52, 67, 70, 69, 94, 90),
operation = { it * it },
test = 17,
ifTrue = 0,
ifFalse = 3,
),
5 to Monkey(
items = mutableListOf(69, 85, 89, 91),
operation = { it + 7 },
test = 13,
ifTrue = 1,
ifFalse = 7,
),
6 to Monkey(
items = mutableListOf(75, 53, 73, 52, 75),
operation = { it * 7 },
test = 2,
ifTrue = 0,
ifFalse = 4,
),
7 to Monkey(
items = mutableListOf(94, 60, 79),
operation = { it + 2 },
test = 3,
ifTrue = 1,
ifFalse = 6,
)
)
private fun exampleMonkeys() = mapOf(
0 to Monkey(
items = mutableListOf(79, 98),
operation = { it * 19 },
test = 23,
ifTrue = 2,
ifFalse = 3,
),
1 to Monkey(
items = mutableListOf(54, 65, 75, 74),
operation = { it + 6 },
test = 19,
ifTrue = 2,
ifFalse = 0,
),
2 to Monkey(
items = mutableListOf(79, 60, 97),
operation = { it * it },
test = 13,
ifTrue = 1,
ifFalse = 3,
),
3 to Monkey(
items = mutableListOf(74),
operation = { it + 3 },
test = 17,
ifTrue = 0,
ifFalse = 1,
)
)
fun solution2(): Long {
val monkeys = realMonkey()
val monkeyCount = mutableMapOf<Int, Long>()
val divide = monkeys.map { it.value.test }.reduce { acc, l -> max(acc, 1) * l }
println("divide $divide")
repeat(10_000) {
monkeys.forEach { x ->
val monkey = x.value
monkeyCount[x.key] = (monkeyCount[x.key] ?: 0L) + monkey.items.size
monkey.items
.map { it % divide }
.map { monkey.operation(it) }
.forEach {
if (it % monkey.test == 0L) {
monkeys[monkey.ifTrue]!!.items.add(it)
} else {
monkeys[monkey.ifFalse]!!.items.add(it)
}
}
monkey.items.clear()
}
}
/*
monkeys.forEach {
println("Monkey ${it.key} -> ${it.value.items}")
}
*/
monkeyCount.forEach {
println("Monkey ${it.key} -> ${it.value}")
}
val best = monkeyCount.map { it.value }.sortedDescending().take(2)
return best[0] * best[1]
}
}
class Monkey(
val items: MutableList<Long>,
val operation: (Long) -> Long,
val test: Long,
val ifTrue: Int,
val ifFalse: Int,
) | 0 | Kotlin | 0 | 0 | f1094ba3ead165adaadce6cffd5f3e78d6505724 | 5,012 | adventofcode-2022 | MIT License |
src/main/kotlin/euler/Problem5.kt | SackCastellon | 575,340,524 | false | {"Kotlin": 21403} | package euler
import kotlin.math.max
/**
* [#5 Smallest multiple - Project Euler](https://projecteuler.net/problem=5)
*/
object Problem5 : Problem<Int> {
override fun solve(): Int {
return (2..20)
.flatMap { it.primeFactors().groupingBy { it }.eachCount().toList() }
.fold(mutableMapOf<Int, Int>()) { acc, (k, v) -> acc.apply { merge(k, v, ::max) } }
.flatMap { (k, v) -> List(v) { k } }
.reduce(Int::times)
}
private fun Int.primeFactors() = sequence {
var n = this@primeFactors
while (n % 2 == 0) {
yield(2)
n /= 2
if (n == 1) return@sequence
}
for (factor in (3..n step 2)) {
while (n % factor == 0) {
yield(factor)
n /= factor
if (n == 1) return@sequence
}
}
}
}
| 0 | Kotlin | 0 | 0 | ac2e95b9d3fa09673b9c7a86f1086a759384190a | 894 | project-euler | Apache License 2.0 |
usvm-util/src/main/kotlin/org/usvm/UMachineOptions.kt | UnitTestBot | 586,907,774 | false | {"Kotlin": 2547205, "Java": 471958} | package org.usvm
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.seconds
enum class SolverType {
YICES,
Z3
}
enum class PathSelectionStrategy {
/**
* Selects the states in depth-first order.
*/
DFS,
/**
* Selects the states in breadth-first order.
*/
BFS,
/**
* Selects the next state by descending from root to leaf in
* symbolic execution tree. The child on each step is selected randomly.
*
* See KLEE's random path search heuristic.
*/
RANDOM_PATH,
/**
* Gives priority to states with shorter path lengths.
* The state with the shortest path is always selected.
*/
DEPTH,
/**
* Gives priority to states with shorter path lengths.
* States are selected randomly with distribution based on path length.
*/
DEPTH_RANDOM,
/**
* Gives priority to states with less number of forks.
* The state with the least number of forks is always selected.
*/
FORK_DEPTH,
/**
* Gives priority to states with less number of forks.
* States are selected randomly with distribution based on number of forks.
*/
FORK_DEPTH_RANDOM,
/**
* Gives priority to states closer to uncovered instructions in application
* graph.
* The closest to uncovered instruction state is always selected.
*/
CLOSEST_TO_UNCOVERED,
/**
* Gives priority to states closer to uncovered instructions in application
* graph.
* States are selected randomly with distribution based on distance to uncovered instructions.
*/
CLOSEST_TO_UNCOVERED_RANDOM,
/**
* Gives priority to the states which are closer to their targets considering interprocedural
* reachability.
* The closest to targets state is always selected.
*/
TARGETED,
/**
* Gives priority to the states which are closer to their targets considering interprocedural
* reachability.
* States are selected randomly with distribution based on distance to targets.
*/
TARGETED_RANDOM,
/**
* Gives priority to the states which are closer to their targets considering only current call stack
* reachability.
* The closest to targets state is always selected.
*/
TARGETED_CALL_STACK_LOCAL,
/**
* Gives priority to the states which are closer to their targets considering only current call stack
* reachability.
* States are selected randomly with distribution based on distance to targets.
*/
TARGETED_CALL_STACK_LOCAL_RANDOM
}
enum class PathSelectorCombinationStrategy {
/**
* Multiple path selectors have the common state set and are interleaved.
*/
INTERLEAVED,
/**
* Multiple path selectors have independent state sets and are interleaved.
*/
PARALLEL
}
enum class PathSelectorFairnessStrategy {
/**
* Strategy similar to Linux Completely Fair Scheduler: method with the lowest time spent is always peeked.
*/
COMPLETELY_FAIR,
/**
* Strategy similar to Linux O(1) scheduler: keys are switched in round-robin fashion (so, all keys are guaranteed to be selected).
* Each key is given an equal time quantum.
*/
CONSTANT_TIME
}
// TODO: add module/package coverage zone
enum class CoverageZone {
/**
* Only target method coverage is considered.
*/
METHOD,
/**
* Coverage of methods in target method's class id considered.
*/
CLASS,
/**
* Coverage of methods transitively reachable from a start method.
*/
TRANSITIVE
}
enum class StateCollectionStrategy {
/**
* Collect only those terminated states which have covered new locations.
*/
COVERED_NEW,
/**
* Collect only those states which have reached terminal targets.
*/
REACHED_TARGET
}
data class UMachineOptions(
/**
* State selection heuristics.
* If multiple heuristics are specified, they are combined according to [pathSelectorCombinationStrategy].
*
* @see PathSelectionStrategy
*/
val pathSelectionStrategies: List<PathSelectionStrategy> = listOf(PathSelectionStrategy.BFS),
/**
* Strategy to combine multiple [pathSelectionStrategies].
*
* @see PathSelectorCombinationStrategy
*/
val pathSelectorCombinationStrategy: PathSelectorCombinationStrategy = PathSelectorCombinationStrategy.INTERLEAVED,
/**
* Strategy to switch between multiple methods' path selectors. Valid only when [timeout] is set.
*
* @see PathSelectorFairnessStrategy
*/
val pathSelectorFairnessStrategy: PathSelectorFairnessStrategy = PathSelectorFairnessStrategy.CONSTANT_TIME,
/**
* Strategy to collect terminated states.
*
* @see StateCollectionStrategy
*/
val stateCollectionStrategy: StateCollectionStrategy = StateCollectionStrategy.COVERED_NEW,
/**
* Seed used for random operations.
*/
val randomSeed: Long = 0,
/**
* Code coverage percent to stop execution on. Considered only if in range [1..100].
*/
val stopOnCoverage: Int = 100,
/**
* Optional limit of symbolic execution steps to stop execution on.
*/
val stepLimit: ULong? = null,
/**
* Optional limit of collected states to stop execution on.
*/
val collectedStatesLimit: Int? = null,
/**
* Timeout to stop execution on. Use [Duration.INFINITE] for no timeout.
*/
val timeout: Duration = 20_000.milliseconds,
/**
* A number of steps from the last terminated state.
*/
val stepsFromLastCovered: Long? = null,
/**
* Scope of methods which coverage is considered.
*
* @see CoverageZone
*/
val coverageZone: CoverageZone = CoverageZone.METHOD,
/**
* Whether we should prefer exceptional state in the queue to the regular ones.
*/
val exceptionsPropagation: Boolean = true,
/**
* SMT solver type used for path constraint solving.
*/
val solverType: SolverType = SolverType.Z3,
/**
* A timeout for checks with the SMT solver.
*/
val solverTimeout: Duration = 1.seconds,
/**
* Whether we use a solver on symbolic branching to fork only with satisfiable states or keep all states.
*/
val useSolverForForks: Boolean = true,
/**
* Whether we should run solver in another process or not.
*/
val runSolverInAnotherProcess: Boolean = false,
/**
* Whether we should try to apply soft constraints for symbolic values.
*/
val useSoftConstraints: Boolean = true,
/**
* A timeout for heavy operations with types.
*/
val typeOperationsTimeout: Duration = 100.milliseconds,
/**
* Should machine stop when all terminal targets are reached.
*/
val stopOnTargetsReached: Boolean = false,
/**
* Depth of the interprocedural reachability search used in distance-based path selectors.
*/
val targetSearchDepth: UInt = 0u,
/**
* Should machine use merging when possible
*/
val useMerging: Boolean = false,
)
| 39 | Kotlin | 0 | 7 | 94c5a49a0812737024dee5be9d642f22baf991a2 | 7,212 | usvm | Apache License 2.0 |
control-core/src/commonMain/kotlin/com.github.oleather.core/geometry/Circle.kt | OLeather | 313,396,280 | false | null | package com.github.oleather.core.geometry
import com.soywiz.korma.geom.Point
import kotlin.math.abs
import kotlin.math.sqrt
public class Circle public constructor(public val radius: Double, public val center: Point) {
//https://cp-algorithms.com/geometry/circle-line-intersection.html
public fun intersection(line: Line): Pair<Point, Point>? {
val centeredLine = Line(line.getPoint(-1.0) - center, line.getPoint(1.0) - center)
val a = centeredLine.a
val b = centeredLine.b
val c = -centeredLine.c
val r = radius
val x = -a * c / (a * a + b * b)
val y = -b * c / (a * a + b * b)
if (c * c > r * r * (a * a + b * b) + 2e-9) {
return null
}
val d = r * r - c * c / (a * a + b * b)
val mult = sqrt(d / (a * a + b * b))
val x0 = x + b * mult
val y0 = y - a * mult
val x1 = x - b * mult
val y1 = y + a * mult
return Pair(Point(x0, y0), Point(x1, y1))
}
//http://paulbourke.net/geometry/circlesphere/
public fun intersection(circle: Circle): Pair<Point, Point>? {
val r0 = radius
val r1 = circle.radius
val p0 = center
val p1 = circle.center
val d = center.distanceTo(circle.center)
if (d > r0 + r1 || d < abs(r0 - r1)) {
return null
}
if (d == 0.0 && r0 == r1) {
return Pair(
Point(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY),
Point(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)
)
}
val a = (r0 * r0 - r1 * r1 + d * d) / (2 * d)
val h = sqrt(r0 * r0 - a * a)
val p2 = p0 + ((p1 - p0) * a) / d
val b = ((p1 - p0) * h) / d
val intersect1 = Point(p2.x + b.y, p2.y - b.x)
val intersect2 = Point(p2.x - b.y, p2.y + b.x)
println(" $p2 $intersect1 $intersect2")
return Pair(intersect1, intersect2)
}
}
| 0 | Kotlin | 0 | 0 | 175a700665d3549539f14dec7ae420747d99f303 | 1,986 | control-theory | MIT License |
src/main/kotlin/tr/emreone/kotlin_utils/extensions/Collections.kt | EmRe-One | 442,916,831 | false | {"Kotlin": 173543} | package tr.emreone.kotlin_utils.extensions
import kotlin.math.max
import kotlin.math.min
/**
*
* @receiver MutableList<Pair<String, Long>>
* @param from MutableList<Pair<String, Long>>
* @param deep Boolean
*/
fun MutableList<Pair<String, Long>>.copy(from: MutableList<Pair<String, Long>>, deep: Boolean = false) {
this.clear()
if (!deep) {
this.addAll(from)
}
else {
from.forEach {
this.add(it.first to it.second)
}
}
}
/**
* Create a permutation of the given list
*
* @receiver List<T>
* @return List<List<T>>
*/
fun <T> List<T>.permutations(): List<List<T>> {
if (size == 1) return listOf(this)
return indices.flatMap { i ->
val rest = subList(0, i) + subList(i + 1, size)
rest.permutations().map {
listOf(this[i]) + it
}
}
}
/*
* POWERSETS
*/
/**
*
* @receiver Collection<T>
* @return Set<Set<T>>
*/
fun <T> Collection<T>.powerset(): Set<Set<T>> = powerset(this, setOf(setOf()))
/**
*
* @param left Collection<T>
* @param acc Set<Set<T>>
* @return Set<Set<T>>
*/
private tailrec fun <T> powerset(left: Collection<T>, acc: Set<Set<T>>): Set<Set<T>> = when {
left.isEmpty() -> acc
else -> powerset(left.drop(1), acc + acc.map { it + left.first() })
}
/*
* COMBINATIONS
*/
/**
* In mathematics, a combination is a way of selecting items from a collection, such that (unlike permutations) the
* order of selection does not matter.
*
* For set {1, 2, 3}, 2 elements combinations are {1, 2}, {2, 3}, {1, 3}.
* All possible combinations is called 'powerset' and can be found as an
* extension function for set under this name
*
* @receiver Set<T>
* @param combinationSize Int
* @return Set<Set<T>>
*/
fun <T> Set<T>.combinations(combinationSize: Int): Set<Set<T>> = when {
combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize")
combinationSize == 0 -> setOf(setOf())
combinationSize >= size -> setOf(toSet())
else -> powerset() // TODO this is not the best implementation
.filter { it.size == combinationSize }
.toSet()
}
/**
*
* @receiver Set<T>
* @param combinationSize Int
* @return Set<Map<T, Int>>
*/
fun <T> Set<T>.combinationsWithRepetitions(combinationSize: Int): Set<Map<T, Int>> = when {
combinationSize < 0 -> throw Error("combinationSize cannot be smaller then 0. It is equal to $combinationSize")
combinationSize == 0 -> setOf(mapOf())
else -> combinationsWithRepetitions(combinationSize - 1)
.flatMap { subset -> this.map { subset + (it to (subset.getOrElse(it) { 0 } + 1)) } }
.toSet()
}
/*
* SPLITS
*/
/**
* Takes set of elements and returns set of splits and each of them is set of sets
*
* @receiver Set<T>
* @param groupsNum Int
* @return Set<Set<Set<T>>>
*/
fun <T> Set<T>.splits(groupsNum: Int): Set<Set<Set<T>>> = when {
groupsNum < 0 -> throw Error("groupsNum cannot be smaller then 0. It is equal to $groupsNum")
groupsNum == 0 -> if (isEmpty()) setOf(emptySet()) else emptySet()
groupsNum == 1 -> setOf(setOf(this))
groupsNum == size -> setOf(this.map { setOf(it) }.toSet())
groupsNum > size -> emptySet()
else -> setOf<Set<Set<T>>>()
.plus(splitsWhereFirstIsAlone(groupsNum))
.plus(splitsForFirstIsInAllGroups(groupsNum))
}
/**
*
* @receiver Set<T>
* @param groupsNum Int
* @return List<Set<Set<T>>>
*/
private fun <T> Set<T>.splitsWhereFirstIsAlone(groupsNum: Int): List<Set<Set<T>>> = this
.minusElement(first())
.splits(groupsNum - 1)
.map { it.plusElement(setOf(first())) }
/**
*
* @receiver Set<T>
* @param groupsNum Int
* @return List<Set<Set<T>>>
*/
private fun <T> Set<T>.splitsForFirstIsInAllGroups(groupsNum: Int): List<Set<Set<T>>> = this
.minusElement(first())
.splits(groupsNum)
.flatMap { split -> split.map { group -> split.minusElement(group).plusElement(group + first()) } }
/**
* Splits elements by a defined [delimiter] predicate into groups of elements.
*
* @param limit limits the number of generated groups.
* @param keepEmpty if true, groups without elements are preserved, otherwise will be omitted in the result.
* @return a List of the groups of elements.
*/
fun <T> Iterable<T>.splitBy(limit: Int = 0, keepEmpty: Boolean = true, delimiter: (T) -> Boolean): List<List<T>> {
require(limit >= 0) { "Limit must not be negative, but was $limit" }
val isLimited = limit > 0
val result = ArrayList<List<T>>(if (isLimited) limit.coerceAtMost(10) else 10)
var currentSubList = mutableListOf<T>()
for (element in this) {
if ((!isLimited || (result.size < limit - 1)) && delimiter(element)) {
if (keepEmpty || currentSubList.isNotEmpty()) {
result += currentSubList
currentSubList = mutableListOf()
}
} else {
currentSubList += element
}
}
if (keepEmpty || currentSubList.isNotEmpty())
result += currentSubList
return result
}
/**
* Splits nullable elements by `null` values. The resulting groups will not contain any nulls.
*
* @param keepEmpty if true, groups without elements are preserved, otherwise will be omitted in the result.
* @return a List of the groups of elements.
*/
@Suppress("UNCHECKED_CAST")
fun <T : Any> Iterable<T?>.splitByNulls(keepEmpty: Boolean = true): List<List<T>> =
splitBy(keepEmpty = keepEmpty) { it == null } as List<List<T>>
fun Pair<Int, Int>.asRange(): IntRange = min(first, second)..max(first, second)
fun Pair<Long, Long>.asRange(): LongRange = min(first, second)..max(first, second)
/**
* Returns the smallest and largest element or `null` if there are no elements.
*/
fun <T : Comparable<T>> Iterable<T>.minMaxOrNull(): Pair<T, T>? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
var max = min
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
if (e > max) max = e
}
return min to max
}
/**
* Returns the smallest and largest element or throws [NoSuchElementException] if there are no elements.
*/
fun <T : Comparable<T>> Iterable<T>.minMax(): Pair<T, T> = minMaxOrNull() ?: throw NoSuchElementException()
/**
* Returns the first element yielding the smallest and the first element yielding the largest value
* of the given function or `null` if there are no elements.
*/
inline fun <T, R : Comparable<R>> Iterable<T>.minMaxByOrNull(selector: (T) -> R): Pair<T, T>? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var maxElem = minElem
if (!iterator.hasNext()) return minElem to maxElem
var minValue = selector(minElem)
var maxValue = minValue
do {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
if (v > maxValue) {
maxElem = e
maxValue = v
}
} while (iterator.hasNext())
return minElem to maxElem
}
/**
* Returns the first element yielding the smallest and the first element yielding the largest value
* of the given function or throws [NoSuchElementException] if there are no elements.
*/
inline fun <T, R : Comparable<R>> Iterable<T>.minMaxBy(selector: (T) -> R): Pair<T, T> =
minMaxByOrNull(selector) ?: throw NoSuchElementException()
/**
* Returns the smallest and largest value as a range or `null` if there are no elements.
*/
fun Iterable<Int>.rangeOrNull(): IntRange? = minMaxOrNull()?.let { it.first..it.second }
/**
* Returns the smallest and largest value as a range or throws [NoSuchElementException] if there are no elements.
*/
fun Iterable<Int>.range(): IntRange = rangeOrNull() ?: throw NoSuchElementException()
/**
* Returns the smallest and largest value as a range or `null` if there are no elements.
*/
fun Iterable<Long>.rangeOrNull(): LongRange? = minMaxOrNull()?.let { it.first..it.second }
/**
* Returns the smallest and largest value as a range or throws [NoSuchElementException] if there are no elements.
*/
fun Iterable<Long>.range(): LongRange = rangeOrNull() ?: throw NoSuchElementException()
/**
* Efficiently generate the top [n] smallest elements without sorting all elements.
*/
@Suppress("DuplicatedCode")
fun <T : Comparable<T>> Iterable<T>.minN(n: Int): List<T> {
require(n >= 0) { "Number of smallest elements must not be negative" }
val iterator = iterator()
when {
n == 0 || !iterator.hasNext() -> return emptyList()
n == 1 -> return minOrNull()?.let { listOf(it) } ?: emptyList()
this is Collection<T> && n >= size -> return this.sorted()
}
val smallest = ArrayList<T>(n.coerceAtMost(10))
var min = iterator.next()
.also { smallest += it }
.let { it to it }
while (iterator.hasNext()) {
val e = iterator.next()
when {
smallest.size < n -> {
smallest += e
min = when {
e < min.first -> e to min.second
e > min.second -> min.first to e
else -> min
}
}
e < min.second -> {
val removeAt = smallest.indexOfLast { it.compareTo(min.second) == 0 }
smallest.removeAt(removeAt)
smallest += e
min = smallest.minMax()
}
}
}
return smallest.sorted()
}
/**
* Efficiently generate the top [n] largest elements without sorting all elements.
*/
@Suppress("DuplicatedCode")
fun <T : Comparable<T>> Iterable<T>.maxN(n: Int): List<T> {
require(n >= 0) { "Number of largest elements must not be negative" }
val iterator = iterator()
when {
n == 0 || !iterator.hasNext() -> return emptyList()
n == 1 -> return maxOrNull()?.let { listOf(it) } ?: emptyList()
this is Collection<T> && n >= size -> return this.sortedDescending()
}
val largest = ArrayList<T>(n.coerceAtMost(10))
var max = iterator.next()
.also { largest += it }
.let { it to it }
while (iterator.hasNext()) {
val e = iterator.next()
when {
largest.size < n -> {
largest += e
max = when {
e < max.first -> e to max.second
e > max.second -> max.first to e
else -> max
}
}
e > max.first -> {
val removeAt = largest.indexOfLast { it.compareTo(max.first) == 0 }
largest.removeAt(removeAt)
largest += e
max = largest.minMax()
}
}
}
return largest.sortedDescending()
}
fun <K, V> Map<K, V>.flip(): Map<V, K> = asIterable().associate { (k, v) -> v to k }
fun Iterable<Long>.product(): Long = reduce(Long::safeTimes)
@JvmName("intProduct")
fun Iterable<Int>.product(): Long = fold(1L, Long::safeTimes)
infix fun Int.safeTimes(other: Int) = (this * other).also {
check(other == 0 || it / other == this) { "Integer Overflow at $this * $other" }
}
infix fun Long.safeTimes(other: Long) = (this * other).also {
check(other == 0L || it / other == this) { "Long Overflow at $this * $other" }
}
infix fun Long.safeTimes(other: Int) = (this * other).also {
check(other == 0 || it / other == this) { "Long Overflow at $this * $other" }
}
infix fun Int.safeTimes(other: Long) = (this.toLong() * other).also {
check(other == 0L || it / other == this.toLong()) { "Long Overflow at $this * $other" }
}
fun Long.checkedToInt(): Int = let {
check(it in Int.MIN_VALUE..Int.MAX_VALUE) { "Value does not fit in Int: $it" }
it.toInt()
}
/**
* Returns a list containing the runs of equal elements and their respective count as Pairs.
*/
fun <T> Iterable<T>.runs(): List<Pair<T, Int>> {
val iterator = iterator()
if (!iterator.hasNext())
return emptyList()
val result = mutableListOf<Pair<T, Int>>()
var current = iterator.next()
var count = 1
while (iterator.hasNext()) {
val next = iterator.next()
if (next != current) {
result.add(current to count)
current = next
count = 0
}
count++
}
result.add(current to count)
return result
}
fun <T> Iterable<T>.runsOf(e: T): List<Int> {
val iterator = iterator()
if (!iterator.hasNext())
return emptyList()
val result = mutableListOf<Int>()
var count = 0
while (iterator.hasNext()) {
val next = iterator.next()
if (next == e) {
count++
} else if (count > 0) {
result.add(count)
count = 0
}
}
if (count > 0)
result.add(count)
return result
}
fun <T> T.applyTimes(n: Int, f: (T) -> T): T = when (n) {
0 -> this
else -> f(this).applyTimes(n - 1, f)
}
| 0 | Kotlin | 0 | 0 | aee38364ca1827666949557acb15ae3ea21881a1 | 13,040 | kotlin-utils | Apache License 2.0 |
src/day01/Day01.kt | TimberBro | 572,681,059 | false | {"Kotlin": 20536} | package day01
import readInput
import separateInputByEmptyLine
import kotlin.streams.toList
fun main() {
fun part1(input: List<String>): Int {
val inputByEmptyLine = separateInputByEmptyLine(input)
val maxValue = inputByEmptyLine
.stream()
.map {
it.stream().mapToInt(String::toInt).sum()
}
.toList()
.max()
return maxValue
}
fun part2(input: List<String>): Int {
val inputByEmptyLine = separateInputByEmptyLine(input)
val sumTopThree = inputByEmptyLine
.asSequence()
.map {
it.stream().mapToInt(String::toInt).sum()
}
.sortedDescending()
.take(3)
.sum()
return sumTopThree
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("day01/Day01_test")
check(part1(testInput) == 24000)
check(part2(testInput) == 45000)
val input = readInput("day01/Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 516a98e5067d11f0e6ff73ae19f256d8c1bfa905 | 1,146 | AoC2022 | Apache License 2.0 |
src/questions/PlusOne.kt | realpacific | 234,499,820 | false | null | package questions
import utils.assertIterableSame
/**
* You are given a large integer represented as an integer array digits, where each digits[i]
* is the ith digit of the integer. The digits are ordered from most significant to least
* significant in left-to-right order. The large integer does not contain any leading 0's.
* Increment the large integer by one and return the resulting array of digits.
*
* [Source](https://leetcode.com/problems/plus-one/)
*/
fun plusOne(digits: IntArray): IntArray {
// If last digit is less than 9, just add 1 and finish e.g: 408 -> 409
if (digits.last() < 9) {
digits[digits.lastIndex] = digits[digits.lastIndex] + 1
return digits
}
// else need to check other digits as well eg: 489 -> 490
return incrementByOneAt(digits, digits.lastIndex)
}
private fun incrementByOneAt(digits: IntArray, index: Int): IntArray {
if (index == -1) {
if (digits[0] == 0) {
// this is the case when the MSB is 0, which means there was a carry over
// but the current array can't hold the carry
// so create new array that includes the carry
return intArrayOf(1, *digits)
}
return digits
}
if (digits[index] == 9) {
// If 9, then make it 0 and process previous bit
digits[index] = 0
// recurse on previous digits
return incrementByOneAt(digits, index - 1)
} else {
// If not 9, increment and finish
digits[index] = digits[index] + 1
return digits
}
}
fun main() {
assertIterableSame(intArrayOf(1, 2, 4).toList(), plusOne(intArrayOf(1, 2, 3)).toList())
assertIterableSame(intArrayOf(4, 3, 2, 2).toList(), plusOne(intArrayOf(4, 3, 2, 1)).toList())
assertIterableSame(intArrayOf(1).toList(), plusOne(intArrayOf(0)).toList())
assertIterableSame(intArrayOf(1, 0).toList(), plusOne(intArrayOf(9)).toList())
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,933 | algorithms | MIT License |
src/main/kotlin/g0901_1000/s0913_cat_and_mouse/Solution.kt | javadev | 190,711,550 | false | {"Kotlin": 4420233, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g0901_1000.s0913_cat_and_mouse
// #Hard #Dynamic_Programming #Math #Graph #Memoization #Topological_Sort #Game_Theory
// #2023_04_16_Time_211_ms_(100.00%)_Space_37.1_MB_(100.00%)
import java.util.LinkedList
import java.util.Queue
class Solution {
fun catMouseGame(graph: Array<IntArray>): Int {
val n = graph.size
val states = Array(n) {
Array(n) {
IntArray(
2
)
}
}
val degree = Array(n) {
Array(n) {
IntArray(
2
)
}
}
for (m in 0 until n) {
for (c in 0 until n) {
degree[m][c][MOUSE] = graph[m].size
degree[m][c][CAT] = graph[c].size
for (node in graph[c]) {
if (node == 0) {
--degree[m][c][CAT]
break
}
}
}
}
val q: Queue<IntArray> = LinkedList()
for (i in 1 until n) {
states[0][i][MOUSE] = MOUSE_WIN
states[0][i][CAT] = MOUSE_WIN
states[i][i][MOUSE] = CAT_WIN
states[i][i][CAT] = CAT_WIN
q.offer(intArrayOf(0, i, MOUSE, MOUSE_WIN))
q.offer(intArrayOf(i, i, MOUSE, CAT_WIN))
q.offer(intArrayOf(0, i, CAT, MOUSE_WIN))
q.offer(intArrayOf(i, i, CAT, CAT_WIN))
}
while (q.isNotEmpty()) {
val state = q.poll()
val mouse = state[0]
val cat = state[1]
val turn = state[2]
val result = state[3]
if (mouse == 1 && cat == 2 && turn == MOUSE) {
return result
}
val prevTurn = 1 - turn
for (prev in graph[if (prevTurn == MOUSE) mouse else cat]) {
val prevMouse = if (prevTurn == MOUSE) prev else mouse
val prevCat = if (prevTurn == CAT) prev else cat
if (prevCat != 0 && states[prevMouse][prevCat][prevTurn] == DRAW &&
(
prevTurn == MOUSE && result == MOUSE_WIN || prevTurn == CAT && result == CAT_WIN ||
--degree[prevMouse][prevCat][prevTurn] == 0
)
) {
states[prevMouse][prevCat][prevTurn] = result
q.offer(intArrayOf(prevMouse, prevCat, prevTurn, result))
}
}
}
return DRAW
}
companion object {
private const val DRAW = 0
private const val MOUSE_WIN = 1
private const val CAT_WIN = 2
private const val MOUSE = 0
private const val CAT = 1
}
}
| 0 | Kotlin | 14 | 24 | fc95a0f4e1d629b71574909754ca216e7e1110d2 | 2,785 | LeetCode-in-Kotlin | MIT License |
src/Day01.kt | iartemiev | 573,038,071 | false | {"Kotlin": 21075} | fun main() {
fun reduceInput(input: List<String>): List<Int> {
val calTotals: MutableList<Int> = mutableListOf(0)
for (line in input) {
if (line.isEmpty()) {
calTotals.add(0)
} else {
val cal = Integer.parseInt(line)
calTotals[calTotals.size - 1] += cal
}
}
calTotals.sortDescending()
return calTotals
}
fun part1(input: List<String>): Int {
return reduceInput(input)[0]
}
fun part2(input: List<String>): Int {
return reduceInput(input).take(3).sum()
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
check(part1(testInput) == 24000)
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 8d2b7a974c2736903a9def65282be91fbb104ffd | 776 | advent-of-code | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions52.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
import com.qiaoyuang.algorithm.round0.Stack
fun test52() {
val (header1, header2) = testData1()
printlnResult(header1, header2)
}
/**
* Questions 52: Find the first public node on two linked lists
*/
private fun <T> findFirstPublicNode(header1: SingleDirectionNode<T>, header2: SingleDirectionNode<T>): SingleDirectionNode<T> {
val findNode1 = FindNode(header1)
findNode1.enterStack()
val findNode2 = FindNode(header2)
findNode2.enterStack()
var node1 = findNode1.pop()
var node2 = findNode2.pop()
if (node1 !== node2)
throw IllegalArgumentException("These two linked list don't have public node")
var publicNode = node1
while (node1 === node2) {
publicNode = node1
node1 = findNode1.pop()
node2 = findNode2.pop()
}
return publicNode
}
private class FindNode<T>(private val header: SingleDirectionNode<T>) {
private val stack = Stack<SingleDirectionNode<T>>()
fun enterStack() {
var pointer: SingleDirectionNode<T>? = header
while (pointer != null) {
stack.push(pointer)
pointer = pointer.next
}
}
fun pop(): SingleDirectionNode<T> = stack.pop()
}
private fun testData1(): Pair<SingleDirectionNode<Int>, SingleDirectionNode<Int>> {
val header1 = SingleDirectionNode(1)
val header2 = SingleDirectionNode(4)
var pointer1 = header1
pointer1.next = SingleDirectionNode(2)
pointer1 = pointer1.next!!
pointer1.next = SingleDirectionNode(3)
pointer1 = pointer1.next!!
val firstPublicNode = SingleDirectionNode(6)
pointer1.next = firstPublicNode
pointer1 = pointer1.next!!
pointer1.next = SingleDirectionNode(7)
var pointer2 = header2
pointer2.next = SingleDirectionNode(5)
pointer2 = pointer2.next!!
pointer2.next = firstPublicNode
return header1 to header2
}
private fun <T> printlnResult(header1: SingleDirectionNode<T>, header2: SingleDirectionNode<T>) {
println("The two linked list:")
printlnLinkedList(header1)
printlnLinkedList(header2)
println("The first public node is: ${findFirstPublicNode(header1, header2).element}")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,205 | Algorithm | Apache License 2.0 |
Bootcamp_00/src/exercise2/src/main/kotlin/Main.kt | Hasuk1 | 740,111,124 | false | {"Kotlin": 120039} | fun main() {
try {
val order = readOrder()
val inputNumber = readInputNumber()
val numberSet = createNumberSet(inputNumber, order)
checkForPrimes(numberSet)
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
fun readOrder(): Boolean {
try {
print("The grouping order is (lower or higher): ")
val orderNumber = readLine() ?: throw NumberFormatException()
return when (orderNumber) {
"higher" -> true
"lower" -> false
else -> throw IllegalArgumentException("Incorrect selection of grouping order.")
}
} catch (e: NumberFormatException) {
throw Exception("Incorrect selection of grouping order.")
} catch (e: IllegalArgumentException) {
throw Exception(e.message)
}
}
fun readInputNumber(): Int {
try {
println("Enter a number: ")
val input = readLine() ?: throw NumberFormatException("An incorrect number has been entered.")
val modifiedInput = if (input.isNotEmpty() && input.first() == '-') input.substring(1) else input
return modifiedInput.toInt()
} catch (e: NumberFormatException) {
throw Exception("An incorrect number has been entered.")
}
}
fun createNumberSet(number: Int, order: Boolean): List<Int> {
val numberSet = mutableListOf<Int>()
val numberDigits = number.toString().toCharArray().map { it.digitToInt() }
val indices = when (order) {
true -> numberDigits.indices
false -> numberDigits.indices.reversed()
}
var currentNumber = 0
for (index in indices) {
currentNumber = currentNumber * 10 + numberDigits[index]
numberSet.add(currentNumber)
}
return numberSet
}
fun checkForPrimes(numberSet: List<Int>) {
println("Result:")
for (num in numberSet) {
if (isPrime(num)) {
println("$num - prime")
} else {
println(num)
}
}
}
fun isPrime(num: Int): Boolean {
if (num < 2) return false
for (i in 2 until num) if (num % i == 0) return false
return true
}
| 0 | Kotlin | 0 | 1 | 1dc4de50dd3cd875e3fe76e3da4a58aa04bb87c7 | 1,947 | Kotlin_bootcamp | MIT License |
src/main/kotlin/fp/kotlin/example/chapter09/solution/9_10_FunListMonoidWithFoldable.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter09.solution
import fp.kotlin.example.chapter09.Foldable
import fp.kotlin.example.chapter09.SumMonoid
/**
*
* 연습문제 9-10
*
* 리스트 모노이드를 ``Foldable`` 타입 클래스의 인스턴스로 만들어서 ``foldLeft`` 함수를 작성하고, ``foldMap`` 함수를 테스트해 보자.
*/
fun main() {
val list1 = Cons(1, Cons(2, Cons(3, Cons(4, Nil))))
require(list1.foldLeft(0) { acc, value -> acc + value } == 10)
require(list1.foldMap({ x -> x + 1 }, SumMonoid()) == 14)
require(list1.foldMap({ x -> x * 2 }, SumMonoid()) == 20)
}
sealed class FunList<out T> : Foldable<T>
object Nil : FunList<Nothing>() {
override fun <B> foldLeft(acc: B, f: (B, Nothing) -> B): B = acc
}
data class Cons<out T>(val head: T, val tail: FunList<T>) : FunList<T>() {
override fun <B> foldLeft(acc: B, f: (B, T) -> B): B = tail.foldLeft(f(acc, head), f)
}
| 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 924 | fp-kotlin-example | MIT License |
leetcode/src/tree/Offer28.kt | zhangweizhe | 387,808,774 | false | null | package tree
import linkedlist.TreeNode
import java.util.*
fun main() {
// 剑指 Offer 28. 对称的二叉树
// https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/
val root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(2)
root.left?.left = TreeNode(3)
root.left?.right = TreeNode(4)
root.right?.left = TreeNode(4)
root.right?.right = TreeNode(3)
println(isSymmetric2(root))
}
private fun isSymmetric(root: TreeNode?): Boolean {
// 递归
return help(root, root)
}
private fun help(left: TreeNode?, right:TreeNode?):Boolean {
if (left == null && right == null) {
return true
}
if (left == null) {
return false
}
if (right == null) {
return false
}
if (right.`val` != left.`val`) {
return false
}
return help(left.left, right.right) && help(left.right, right.left)
}
private fun isSymmetric1(root: TreeNode?): Boolean {
// 迭代,借助队列结构,检验当前层的同时,把下一层的节点加入队列中,检验完了把当前层出队
if (root == null) {
return true
}
val queue = LinkedList<TreeNode?>()
queue.offer(root)
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val left = queue[i]
val right = queue[size - 1 - i]
if (left == null && right == null) {
continue
}
if (left == null) {
return false
}
if (right == null) {
return false
}
if (left.`val` != right.`val`) {
return false
}
// 把字节点再加进来
queue.offer(left.left)
queue.offer(left.right)
}
// 当前队列结构 (头)当前层 | 下一层(尾)
for (i in 0 until size) {
// 把当前层poll出去
queue.poll()
}
}
return true
}
fun isSymmetric2(root: TreeNode?): Boolean {
if (root == null) {
return true
}
val queue = LinkedList<TreeNode?>()
queue.offer(root)
while (queue.isNotEmpty()) {
val size = queue.size
for (i in 0 until size) {
val left = queue.get(i)
val right = queue.get(size - 1 - i)
if (left == null && right == null) {
continue
}
if (left == null) {
return false
}
if (right == null) {
return false
}
if (left.`val` != right.`val`) {
return false
}
queue.offer(left.left)
queue.offer(left.right)
}
for (i in 0 until size) {
queue.poll()
}
}
return true
}
| 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 2,880 | kotlin-study | MIT License |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round1/Questions17.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round1
fun test17() {
println1toBiggest(1u)
println1toBiggest(2u)
println1toBiggest(3u)
printlnResult2("123456", "5678")
printlnResult2("9999999", "1")
printlnResult2("5555", "5555")
printlnResult2("0", "0")
printlnResult2("-123456", "-5678")
printlnResult2("-999999", "-1")
printlnResult2("-5555", "-5555")
printlnResult2("123456", "-5678")
printlnResult2("-9999999", "1")
printlnResult2("5555", "-5555")
}
/**
* Questions 17-1: Give a number n, print the 1 to the biggest number(n digits).
*/
private fun println1toBiggest(n: UInt) {
if (n == 0u)
throw IllegalArgumentException("The n must great than 0")
print("The sequence is: ")
val biggest = buildString {
repeat(n.toInt()) {
append('9')
}
}
val numberBuilder = StringBuilder("1")
var number = numberBuilder.toString()
while (number != biggest) {
print("$number, ")
for (i in numberBuilder.lastIndex downTo 0) {
val charI = numberBuilder[i]
if (charI == '9') {
numberBuilder[i] = '0'
if (i == 0)
numberBuilder.insert(0, 1)
} else {
numberBuilder[i] = (charI.digitToInt() + 1).digitToChar()
break
}
}
number = numberBuilder.toString()
}
println("$number;")
}
/**
* Questions 17-2: Use String to implement the addition of two integer
*/
private infix fun String.add(target: String): String = when {
first() == '-' && target.first() == '-' -> {
val (small, big) = if (length < target.length)
this to target
else
target to this
twoNegative(small, big)
}
first() != '-' && target.first() != '-' -> {
val (small, big) = if (length < target.length)
this to target
else
target to this
twoPositive(small, big)
}
else -> {
val (positive, negative) = if (first() == '-') target to this else this to target
positiveAndNegative(positive, negative)
}
}
private fun twoPositive(small: String, big: String): String = buildString {
val diff = big.length - small.length
var carry = 0
for (smallIndex in small.lastIndex downTo 0) {
val bigIndex = smallIndex + diff
val sum = (small[smallIndex].digitToInt() + big[bigIndex].digitToInt() + carry).toString()
append(sum.last())
carry = if (sum.length > 1) sum.first().digitToInt() else 0
}
val startIndex = diff - 1
if (startIndex > 0) for (i in startIndex downTo 0) {
val sum = (big[i].digitToInt() + carry).toString()
append(sum.last())
carry = if (sum.length > 1) sum.first().digitToInt() else 0
}
if (carry > 0)
append(carry)
}.reversed()
private fun twoNegative(small: String, big: String): String = buildString {
var smallIndex = small.lastIndex
var bigIndex = big.lastIndex
var carry = 0
while (bigIndex > 0) {
val sum = if (smallIndex > 0)
(small[smallIndex--].digitToInt() + big[bigIndex--].digitToInt() + carry).toString()
else
(big[bigIndex--].digitToInt() + carry).toString()
append(sum.last())
carry = if (sum.length > 1) sum.first().digitToInt() else 0
}
if (carry > 0)
append(carry)
append('-')
}.reversed()
private fun positiveAndNegative(positive: String, negative: String): String = buildString {
var isAbsPositiveBigger = true
val (big, small) = when {
positive.length > negative.lastIndex -> positive to negative
positive.length < negative.lastIndex -> {
isAbsPositiveBigger = false
negative to positive
}
else -> {
var result = 0
for (i in 0..positive.lastIndex) {
when {
positive[i] > negative[i + 1] -> {
result = 1
break
}
positive[i] < negative[i + 1] -> {
result = -1
isAbsPositiveBigger = false
break
}
}
}
when {
result > 0 -> positive to negative
result < 0 -> {
isAbsPositiveBigger = false
negative to positive
}
else -> {
append('0')
return@buildString
}
}
}
}
var smallIndex = small.lastIndex
var bigIndex = big.lastIndex
var carry = 0
val (bigFinalIndex, smallFinalIndex) = if (isAbsPositiveBigger) intArrayOf(0, 1) else intArrayOf(1, 0)
while (bigIndex >= bigFinalIndex) {
val bigDigital = big[bigIndex--].digitToInt()
val subtrahend = if (smallIndex >= smallFinalIndex)
small[smallIndex--].digitToInt() + carry
else
carry
val sub = if (bigDigital >= subtrahend) {
carry = 0
bigDigital - subtrahend
} else {
carry = 1
bigDigital + 10 - subtrahend
}
append(sub.toString().last())
}
if (!isAbsPositiveBigger)
append('-')
}.reversed()
private fun printlnResult2(num1: String, num2: String) {
val sum = num1 add num2
println("The sum of $num1 and $num2 is ${num1 add num2}, is the result correct: ${sum.toInt() == (num1.toInt() + num2.toInt())}")
}
| 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 5,623 | Algorithm | Apache License 2.0 |
src/year_2023/day_16/Day16.kt | scottschmitz | 572,656,097 | false | {"Kotlin": 240069} | package year_2023.day_16
import readInput
import util.*
interface Mirror {
fun reflect(fromDirection: Direction): Direction
}
object ForwardSlash: Mirror {
override fun reflect(fromDirection: Direction): Direction {
return when (fromDirection) {
Direction.NORTH -> Direction.EAST
Direction.EAST -> Direction.NORTH
Direction.WEST -> Direction.SOUTH
Direction.SOUTH -> Direction.WEST
else -> throw IllegalArgumentException()
}
}
}
object BackSlash: Mirror {
override fun reflect(fromDirection: Direction): Direction {
return when (fromDirection) {
Direction.NORTH -> Direction.WEST
Direction.EAST -> Direction.SOUTH
Direction.WEST -> Direction.NORTH
Direction.SOUTH -> Direction.EAST
else -> throw IllegalArgumentException()
}
}
}
enum class Splitter {
UP_DOWN,
LEFT_RIGHT;
}
data class Layout(
val height: Int,
val width: Int,
val mirrors: Map<Point, Mirror>,
val splitters: Map<Point, Splitter>
)
object Day16 {
/**
*
*/
fun solutionOne(text: List<String>): Int {
val layout = parseLayout(text)
layout.splitters.keys.maxBy { it.second }
val tilesVisitedTop = mutableListOf<Pair<Point, Direction>>()
followPath(-1 to 0, Direction.EAST, layout, tilesVisitedTop)
// -1 to remove -1,0
return tilesVisitedTop.distinctBy { it.first }.size - 1
}
/**
*
*/
fun solutionTwo(text: List<String>): Int {
val layout = parseLayout(text)
var currentMax = 0
// enter from the top and bottom
for (x in 0 .. layout.width) {
val tilesVisitedTop = mutableListOf<Pair<Point, Direction>>()
followPath(x to -1, Direction.SOUTH, layout, tilesVisitedTop)
val fromTop = tilesVisitedTop.distinctBy { it.first }.size - 1
if (fromTop > currentMax) {
currentMax = fromTop
}
val tilesVisitedBottom = mutableListOf<Pair<Point, Direction>>()
followPath(x to layout.height - 1, Direction.NORTH, layout, tilesVisitedBottom)
val fromBottom = tilesVisitedBottom.distinctBy { it.first }.size - 1
if (fromBottom > currentMax) {
currentMax = fromBottom
}
}
// enter from the left and right
for (y in 0 .. layout.height) {
val tilesVisitedLeft = mutableListOf<Pair<Point, Direction>>()
followPath(-1 to y, Direction.EAST, layout, tilesVisitedLeft)
val fromLeft = tilesVisitedLeft.distinctBy { it.first }.size - 1
if (fromLeft > currentMax) {
currentMax = fromLeft
}
val tilesVisitedRight = mutableListOf<Pair<Point, Direction>>()
followPath(layout.width -1 to y, Direction.WEST, layout, tilesVisitedRight)
val fromRight = tilesVisitedRight.distinctBy { it.first }.size - 1
if (fromRight > currentMax) {
currentMax = fromRight
}
}
return currentMax
}
private fun parseLayout(text: List<String>): Layout {
val mirrors = mutableMapOf<Point, Mirror>()
val splitters = mutableMapOf<Point, Splitter>()
text.forEachIndexed { y, line ->
line.forEachIndexed { x, char ->
when (char) {
'/' -> mirrors[x to y] = ForwardSlash
'\\' -> mirrors[x to y] = BackSlash
'-' -> splitters[x to y] = Splitter.LEFT_RIGHT
'|' -> splitters[x to y] = Splitter.UP_DOWN
}
}
}
return Layout(
text.size,
text[0].length,
mirrors,
splitters
)
}
private fun followPath(point: Point, direction: Direction, layout: Layout, previouslyVisitedTiles: MutableList<Pair<Point, Direction>>) {
var currPoint = point
var currDirection = direction
while (currPoint to currDirection !in previouslyVisitedTiles) {
previouslyVisitedTiles.add(currPoint to currDirection)
currPoint = when (currDirection) {
Direction.NORTH -> currPoint.up()
Direction.EAST -> currPoint.right()
Direction.SOUTH -> currPoint.down()
Direction.WEST -> currPoint.left()
else -> throw IllegalArgumentException("invalid direction.")
}
if (currPoint in layout.mirrors) {
val mirror = layout.mirrors[currPoint]!!
currDirection = mirror.reflect(currDirection)
} else if (currPoint in layout.splitters) {
val splitter = layout.splitters[currPoint]!!
when (splitter) {
Splitter.LEFT_RIGHT -> {
if (currDirection == Direction.NORTH || currDirection == Direction.SOUTH) {
followPath(currPoint, Direction.EAST, layout, previouslyVisitedTiles)
followPath(currPoint, Direction.WEST, layout, previouslyVisitedTiles)
break
}
}
Splitter.UP_DOWN -> {
if (currDirection == Direction.EAST || currDirection == Direction.WEST) {
followPath(currPoint, Direction.NORTH, layout, previouslyVisitedTiles)
followPath(currPoint, Direction.SOUTH, layout, previouslyVisitedTiles)
break
}
}
}
}
if (currPoint.x() < 0 || currPoint.x() >= layout.width || currPoint.y() < 0 || currPoint.y() >= layout.height) {
break
}
}
}
}
fun main() {
val text = readInput("year_2023/day_16/Day16.txt")
val solutionOne = Day16.solutionOne(text)
println("Solution 1: $solutionOne")
val solutionTwo = Day16.solutionTwo(text)
println("Solution 2: $solutionTwo")
}
| 0 | Kotlin | 0 | 0 | 70efc56e68771aa98eea6920eb35c8c17d0fc7ac | 6,214 | advent_of_code | Apache License 2.0 |
src/main/kotlin/me/grison/aoc/y2021/Day09.kt | agrison | 315,292,447 | false | {"Kotlin": 267552} | package me.grison.aoc.y2021
import me.grison.aoc.*
import kotlin.Int.Companion.MAX_VALUE
class Day09 : Day(9, 2021) {
override fun title() = "Smoke Basin"
private var dimensions = p(0, 0)
private val grid = loadGrid()
override fun partOne() =
gridPositions(dimensions)
.map { pos -> p(pos, grid.getValue(pos)) }
.filter { (pos, value) -> pos.directions().all { value < grid.getValue(it) } }
.sumOf { (_, value) -> value + 1 }
override fun partTwo() =
gridPositions(dimensions)
.map { pos -> p(pos, grid.getValue(pos)) }
.filter { (_, value) -> value < 9 }
.map { (pos, _) -> basin(pos) }
.fold(hashBag<Position>()) { hash, b -> hash.increase(b) }
.values.sortedDescending().take(3).product()
private fun loadGrid(): Map<Position, Int> =
inputList.let {
dimensions = p(it[0].length, it.size)
it.intGrid(MAX_VALUE)
}
private val basin = { pos: Position -> findBasin(pos) }.memoize()
private fun findBasin(pos: Position): Position =
pos.directions().firstOrNull { grid.getValue(it) < grid.getValue(pos) }
?.let { basin(it) } ?: pos
}
| 0 | Kotlin | 3 | 18 | ea6899817458f7ee76d4ba24d36d33f8b58ce9e8 | 1,244 | advent-of-code | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/pr0gramm/app/services/Graph.kt | mopsalarm | 30,804,448 | false | {"Kotlin": 1404981, "Shell": 6752, "Python": 1124} | package com.pr0gramm.app.services
/**
* A simple graph of double values.
*/
data class Graph(val firstX: Double, val lastX: Double, val points: List<Graph.Point>) {
constructor(points: List<Graph.Point>) : this(points.first().x, points.last().x, points)
val range = firstX.rangeTo(lastX)
val first get() = points.first()
val last get() = points.last()
val isEmpty: Boolean
get() = points.isEmpty()
val maxValue: Double
get() {
return points.maxOf { it.y }
}
val minValue: Double
get() {
return points.minOf { it.y }
}
operator fun get(idx: Int): Point {
return points[idx]
}
data class Point(val x: Double, val y: Double)
fun sampleEquidistant(steps: Int, start: Double = range.start, end: Double = range.endInclusive): Graph {
return Graph((0 until steps).map { idx ->
// the x position that is at the sampling point
val x = start + (end - start) * idx / (steps - 1)
val y = valueAt(x)
Point(x, y)
})
}
fun valueAt(x: Double): Double {
// find first point that is right of our query point.
val largerIndex = points.indexOfFirst { it.x >= x }
if (largerIndex == -1) {
// we did not found a point that is right of x, so we take the value of the
// right most point we know.
return last.y
}
if (largerIndex == 0) {
// the left-most point is already right of x, so take value of the first point.
return first.y
}
// get points a and b.
val a = points[largerIndex - 1]
val b = points[largerIndex]
// interpolate the value at x between a.x and b.x using m as the ascend
val m = (b.y - a.y) / (b.x - a.x)
return a.y + m * (x - a.x)
}
}
fun <T> optimizeValuesBy(values: List<T>, get: (T) -> Double): List<T> {
return values.filterIndexed { idx, value ->
val v = get(value)
idx == 0 || idx == values.size - 1 || get(values[idx - 1]) != v || v != get(values[idx + 1])
}
}
| 28 | Kotlin | 41 | 281 | 6e974f9a1ea188e9fcdd2ebde8faf976311772f4 | 2,157 | Pr0 | MIT License |
src/main/kotlin/_2019/Day13.kt | thebrightspark | 227,161,060 | false | {"Kotlin": 548420} | package _2019
import aocRun
fun main() {
aocRun(puzzleInput) { input ->
val computer = IntcodeComputer(input).apply { printOut = false }
val screen = runGame(computer)
printScreen(screen)
return@aocRun screen.numBlocks
}
aocRun(puzzleInput) { input ->
val computer = IntcodeComputer(input).apply {
printOut = false
code[0] = 2
}
val screen = runGame(computer)
return@aocRun screen.score
}
}
private fun runGame(computer: IntcodeComputer): Screen {
val screen = Screen()
val outputList = mutableListOf<Int>()
computer.input = { screen.calcJoystickInput() }
computer.execute {
if (lastOutput.isNotBlank()) {
outputList += lastOutput.toInt()
clearLastOutput()
if (outputList.size == 3) {
screen[TilePos(outputList[0], outputList[1])] = outputList[2]
outputList.clear()
}
}
}
return screen
}
private fun printScreen(screen: Screen) {
val min = TilePos(Int.MAX_VALUE, Int.MAX_VALUE)
val max = TilePos(Int.MIN_VALUE, Int.MIN_VALUE)
screen.tiles.keys.forEach {
if (it.x < min.x) min.x = it.x
if (it.x > max.x) max.x = it.x
if (it.y < min.y) min.y = it.y
if (it.y > max.y) max.y = it.y
}
val pos = TilePos(0, 0)
val sb = StringBuilder()
(min.y..max.y).forEach { y ->
(min.x..max.x).forEach {
sb.append(
screen[pos.apply {
this.x = it
this.y = y
}]?.char ?: Tile.EMPTY.char
).append(" ")
}
sb.append("\n")
}
sb.append("Score: ").append(screen.score)
println(sb.toString())
}
private class Screen {
val tiles = mutableMapOf<TilePos, Tile>()
var score = 0
var numBlocks = 0
private set
private var paddlePos: TilePos? = null
private var ballPos: TilePos? = null
fun isInitialised() = paddlePos != null && ballPos != null
fun getPaddlePos() = paddlePos!!
fun getBallPos() = ballPos!!
fun calcJoystickInput(): Long = if (isInitialised())
when {
getBallPos().x < getPaddlePos().x -> -1
getBallPos().x > getPaddlePos().x -> 1
else -> 0
}
else 0
operator fun get(key: TilePos) = tiles[key]
operator fun set(key: TilePos, value: Int) {
if (key.x == -1 && key.y == 0) {
score = value
return
}
val tile = Tile.values()[value]
val oldVal = tiles[key]
tiles[key] = tile
when (tile) {
Tile.BLOCK -> if (oldVal != Tile.BLOCK) numBlocks++
Tile.PADDLE -> paddlePos = key
Tile.BALL -> ballPos = key
else -> Unit
}
// if (isInitialised())
// println("$key = $tile")
}
}
private enum class Tile(val char: Char) {
EMPTY(' '),
WALL('#'),
BLOCK('+'),
PADDLE('='),
BALL('O')
}
private data class TilePos(var x: Int, var y: Int)
private const val puzzleInput =
"1,380,379,385,1008,2415,504308,381,1005,381,12,99,109,2416,1101,0,0,383,1102,1,0,382,20101,0,382,1,20102,1,383,2,21102,1,37,0,1106,0,578,4,382,4,383,204,1,1001,382,1,382,1007,382,37,381,1005,381,22,1001,383,1,383,1007,383,24,381,1005,381,18,1006,385,69,99,104,-1,104,0,4,386,3,384,1007,384,0,381,1005,381,94,107,0,384,381,1005,381,108,1105,1,161,107,1,392,381,1006,381,161,1101,-1,0,384,1105,1,119,1007,392,35,381,1006,381,161,1101,0,1,384,20102,1,392,1,21102,22,1,2,21102,1,0,3,21101,0,138,0,1106,0,549,1,392,384,392,21002,392,1,1,21102,1,22,2,21102,1,3,3,21102,1,161,0,1105,1,549,1102,0,1,384,20001,388,390,1,20101,0,389,2,21101,0,180,0,1106,0,578,1206,1,213,1208,1,2,381,1006,381,205,20001,388,390,1,21002,389,1,2,21102,205,1,0,1105,1,393,1002,390,-1,390,1102,1,1,384,21002,388,1,1,20001,389,391,2,21102,228,1,0,1106,0,578,1206,1,261,1208,1,2,381,1006,381,253,20101,0,388,1,20001,389,391,2,21101,253,0,0,1105,1,393,1002,391,-1,391,1102,1,1,384,1005,384,161,20001,388,390,1,20001,389,391,2,21101,279,0,0,1106,0,578,1206,1,316,1208,1,2,381,1006,381,304,20001,388,390,1,20001,389,391,2,21101,0,304,0,1106,0,393,1002,390,-1,390,1002,391,-1,391,1102,1,1,384,1005,384,161,21001,388,0,1,21001,389,0,2,21101,0,0,3,21102,1,338,0,1105,1,549,1,388,390,388,1,389,391,389,20102,1,388,1,20102,1,389,2,21101,0,4,3,21101,0,365,0,1105,1,549,1007,389,23,381,1005,381,75,104,-1,104,0,104,0,99,0,1,0,0,0,0,0,0,286,16,19,1,1,18,109,3,22102,1,-2,1,22102,1,-1,2,21101,0,0,3,21101,0,414,0,1106,0,549,21202,-2,1,1,22101,0,-1,2,21102,429,1,0,1105,1,601,2101,0,1,435,1,386,0,386,104,-1,104,0,4,386,1001,387,-1,387,1005,387,451,99,109,-3,2106,0,0,109,8,22202,-7,-6,-3,22201,-3,-5,-3,21202,-4,64,-2,2207,-3,-2,381,1005,381,492,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,481,21202,-4,8,-2,2207,-3,-2,381,1005,381,518,21202,-2,-1,-1,22201,-3,-1,-3,2207,-3,-2,381,1006,381,507,2207,-3,-4,381,1005,381,540,21202,-4,-1,-1,22201,-3,-1,-3,2207,-3,-4,381,1006,381,529,21201,-3,0,-7,109,-8,2105,1,0,109,4,1202,-2,37,566,201,-3,566,566,101,639,566,566,2102,1,-1,0,204,-3,204,-2,204,-1,109,-4,2106,0,0,109,3,1202,-1,37,594,201,-2,594,594,101,639,594,594,20101,0,0,-2,109,-3,2106,0,0,109,3,22102,24,-2,1,22201,1,-1,1,21101,449,0,2,21102,721,1,3,21101,888,0,4,21102,1,630,0,1105,1,456,21201,1,1527,-2,109,-3,2106,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,2,2,0,2,2,2,0,2,2,2,0,2,2,2,2,0,0,2,2,0,2,0,0,2,0,2,2,2,2,0,2,0,0,1,1,0,0,2,0,0,0,2,0,2,2,0,0,0,2,2,2,0,0,0,2,2,2,0,2,2,0,0,0,0,0,0,0,2,0,0,1,1,0,0,2,0,2,0,2,0,2,0,2,2,0,2,0,2,0,2,2,2,0,0,2,2,2,0,2,0,2,2,2,2,0,0,0,1,1,0,0,2,0,0,0,0,2,0,0,0,2,0,0,2,2,2,2,2,2,2,0,0,0,0,2,2,2,2,2,0,2,2,2,0,1,1,0,2,2,2,0,0,2,2,2,2,2,2,0,2,0,0,0,2,0,0,2,2,2,0,2,0,2,0,2,0,0,2,2,2,0,1,1,0,0,2,2,2,2,0,2,0,2,0,0,2,0,2,2,2,2,2,0,2,0,2,2,0,2,0,2,2,2,0,2,2,0,0,1,1,0,0,0,0,2,2,2,2,2,0,0,2,0,0,0,0,2,0,2,2,0,2,2,2,2,2,0,2,2,0,0,0,2,2,0,1,1,0,2,0,2,2,2,0,0,0,0,0,0,0,2,2,2,2,2,2,2,0,2,0,2,2,0,2,0,2,0,0,0,0,0,0,1,1,0,0,0,2,2,0,0,2,0,0,2,2,2,2,2,0,0,2,2,2,2,0,2,0,0,0,2,2,2,0,2,2,2,2,0,1,1,0,0,0,0,0,2,0,2,2,2,0,0,2,2,2,0,2,2,2,0,0,2,2,0,2,2,2,2,0,0,2,2,2,0,0,1,1,0,0,2,0,2,2,2,2,0,0,0,0,2,0,0,0,2,0,0,0,0,2,0,0,0,0,2,2,0,0,0,2,2,2,0,1,1,0,0,2,0,2,2,2,2,0,0,0,0,0,2,2,2,2,2,2,0,0,2,2,0,2,0,0,2,2,2,2,2,2,0,0,1,1,0,0,2,0,2,0,0,0,0,0,0,2,0,0,0,0,0,0,0,2,2,2,2,0,2,0,2,2,2,2,0,2,0,2,0,1,1,0,0,2,2,2,0,2,2,2,2,0,2,0,2,0,2,0,0,0,0,0,0,2,2,0,2,2,2,2,0,0,2,2,0,0,1,1,0,0,0,2,0,2,2,2,0,0,2,2,2,0,2,0,0,2,2,2,0,2,0,2,2,0,2,2,2,2,0,0,0,0,0,1,1,0,2,2,0,2,2,0,2,0,2,2,2,2,0,2,2,0,2,2,2,0,2,0,0,0,2,0,2,0,0,0,0,0,2,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,72,24,61,53,70,95,17,71,27,25,75,75,9,41,47,87,93,47,92,11,93,87,16,9,94,89,5,46,23,64,39,44,23,93,27,28,10,82,54,70,26,84,86,88,64,20,6,8,8,27,46,80,6,57,15,35,55,86,30,72,88,50,49,11,31,76,89,50,24,13,71,45,35,46,57,14,84,36,1,41,48,87,67,92,83,28,41,7,33,60,66,16,46,42,49,47,53,27,60,84,63,32,23,17,67,61,56,7,31,68,43,50,37,36,56,6,65,35,9,56,15,32,64,68,7,52,30,15,55,71,57,97,31,60,37,35,85,96,59,14,83,76,47,71,65,39,37,22,77,90,60,38,29,72,11,49,40,20,26,19,80,83,58,67,50,94,79,62,86,57,76,44,36,37,55,67,6,26,34,63,80,33,64,45,39,93,70,26,4,71,79,71,21,70,31,48,58,50,54,74,53,31,89,78,57,70,52,70,85,68,5,1,55,12,25,74,81,36,3,3,8,97,9,62,58,80,45,87,45,17,80,62,25,63,29,97,84,55,11,28,86,55,39,81,93,48,67,46,62,79,58,63,87,66,89,23,81,95,22,41,29,87,30,14,67,94,13,7,32,56,66,29,89,77,17,54,12,82,59,83,89,65,72,56,78,97,5,24,20,27,5,37,66,68,77,16,9,66,41,43,18,94,84,86,42,25,47,72,7,8,93,28,68,6,75,55,44,36,15,71,9,49,66,80,77,81,13,7,73,1,86,17,80,36,12,57,42,1,50,87,74,37,60,91,92,46,75,1,17,83,65,49,61,44,13,69,36,90,10,35,61,53,66,11,62,33,14,58,24,82,11,68,48,20,96,68,56,57,77,71,24,41,46,81,43,55,96,30,69,63,23,86,55,83,1,23,88,88,20,66,39,23,26,2,21,80,57,68,3,88,68,1,76,67,84,63,89,45,84,20,97,29,97,7,92,84,65,49,31,93,63,30,89,96,93,37,15,97,30,69,39,1,22,68,5,75,38,39,62,19,24,30,38,36,27,93,1,3,27,39,69,3,86,42,92,81,18,37,16,94,1,94,47,81,51,25,11,6,25,28,78,50,89,39,6,41,27,31,22,17,33,76,2,36,64,79,14,81,91,11,45,12,17,57,70,17,49,54,45,83,71,68,25,89,62,4,55,73,77,98,1,1,36,11,12,78,56,71,96,55,85,71,49,57,68,14,76,63,22,60,79,11,61,49,39,36,33,59,73,85,8,38,3,21,65,21,31,69,54,85,38,26,5,73,43,87,15,44,80,10,92,54,75,96,26,53,84,37,1,76,53,77,68,13,67,64,11,31,32,86,85,71,98,37,53,45,3,3,87,20,20,36,95,87,41,74,23,76,78,19,45,57,41,89,1,11,42,85,74,13,3,72,19,20,64,25,51,82,97,45,55,37,86,2,25,40,26,78,76,16,11,14,36,96,89,90,64,96,79,32,17,47,79,80,53,19,26,59,74,54,53,58,32,48,9,64,96,3,20,88,1,92,44,45,10,4,67,91,81,26,40,89,83,53,83,84,18,53,6,94,51,59,27,38,41,63,2,8,48,64,4,90,88,21,14,37,68,46,1,73,21,14,41,65,81,97,56,90,24,30,81,68,19,16,47,65,53,68,26,54,26,56,15,25,83,89,20,92,4,49,37,42,5,54,7,27,43,36,85,41,59,44,33,93,45,46,23,19,52,20,87,25,85,21,22,20,43,70,35,33,27,17,23,9,56,33,53,55,22,91,69,73,20,23,86,95,14,24,59,60,37,48,94,69,86,63,39,50,84,85,46,65,4,42,97,12,66,37,89,47,29,59,25,47,74,44,24,22,73,45,60,70,11,40,83,49,95,17,9,85,2,27,90,60,32,87,62,36,91,38,19,92,2,33,30,17,43,13,81,53,93,75,14,67,97,95,53,20,63,5,45,63,84,92,65,65,70,33,11,79,82,89,36,59,90,74,6,74,17,96,40,72,89,84,51,17,40,42,504308" | 0 | Kotlin | 0 | 0 | ac62ce8aeaed065f8fbd11e30368bfe5d31b7033 | 9,802 | AdventOfCode | Creative Commons Zero v1.0 Universal |
src/day15/Day15.kt | Ciel-MC | 572,868,010 | false | {"Kotlin": 55885} | package day15
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import readInput
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
val sensorBeaconRegex =
Regex("""Sensor at x=(?<sensorX>-?\d+), y=(?<sensorY>-?\d+): closest beacon is at x=(?<beaconX>-?\d+), y=(?<beaconY>-?\d+)""")
fun String.parsePositions(): Pair<Position, Position> {
val match = sensorBeaconRegex.matchEntire(this) ?: throw IllegalArgumentException("Invalid input: $this")
val sensorX = match.groups["sensorX"]!!.value.toInt()
val sensorY = match.groups["sensorY"]!!.value.toInt()
val beaconX = match.groups["beaconX"]!!.value.toInt()
val beaconY = match.groups["beaconY"]!!.value.toInt()
return Position(sensorX, sensorY) to Position(beaconX, beaconY)
}
data class Position(val x: Int, val y: Int) {
fun distanceTo(other: Position): Int {
return abs(x - other.x) + abs(y - other.y)
}
fun distanceTo(x: Int, y: Int): Int {
return abs(this.x - x) + abs(this.y - y)
}
}
data class Signal(val sensor: Position, val signal: Int) {
fun isInRange(x: Int, y: Int): Boolean {
return sensor.distanceTo(x, y) <= signal
}
companion object {
operator fun invoke(sensor: Position, beacon: Position): Signal {
val signal = sensor.distanceTo(beacon)
return Signal(sensor, signal)
}
}
}
class World {
var xRange = IntRange.EMPTY
var yRange = IntRange.EMPTY
private val signals = mutableSetOf<Signal>()
private val beacons = mutableSetOf<Position>()
fun addSignal(sensor: Position, beacon: Position) {
val distance = sensor.distanceTo(beacon)
val minX = sensor.x - distance
val maxX = sensor.x + distance
val minY = sensor.y - distance
val maxY = sensor.y + distance
xRange = min(xRange.first, minX)..max(xRange.last, maxX)
yRange = min(yRange.first, minY)..max(yRange.last, maxY)
signals.add(Signal(sensor, distance))
beacons.add(beacon)
}
enum class Property {
UNKNOWN, BEACON, NOT_BEACON
}
fun propertyOf(x: Int, y: Int): Property = when {
beacons.contains(Position(x, y)) -> Property.BEACON
signals.any { it.isInRange(x, y) } -> Property.NOT_BEACON
else -> Property.UNKNOWN
}
}
fun Int.around(distance: Int): IntRange {
return (this - distance)..(this + distance)
}
class RowWorld(private val row: Int) {
val ranges = mutableSetOf<IntRange>()
fun addSignal(sensor: Position, beacon: Position) {
// println("Row world $row: Adding signal $sensor -> $beacon")
val distance = sensor.distanceTo(beacon)
// Check if it even concerns our row
if (row !in sensor.y.around(distance)) return
val yDiff = row - sensor.y
ranges.add(sensor.x.around(distance - abs(yDiff)))
}
}
fun MutableCollection<IntRange>.merge() {
val sorted = this.sortedBy { it.first }
this.clear()
var current = sorted.first()
for (range in sorted.drop(1)) {
current = if (range.first in current) {
current.first..max(current.last, range.last)
} else {
add(current)
range
}
}
add(current)
}
fun main() {
fun part1(input: List<String>, row: Int): Int {
val world = World()
input.map(String::parsePositions).forEach { (sensor, beacon) ->
world.addSignal(sensor, beacon)
}
var counter = 0
for (x in world.xRange) {
if (world.propertyOf(x, row) == World.Property.NOT_BEACON) {
counter++
}
}
return counter
}
fun part2(input: List<String>, gridSize: Int): Int {
val detections = input.map(String::parsePositions)
val channel = Channel<Int>()
return runBlocking(Dispatchers.Default) {
val jobs = mutableListOf<Job>()
for (y in 0..gridSize) {
launch {
val rowWorld = RowWorld(y)
detections.forEach { (sensor, beacon) ->
rowWorld.addSignal(sensor, beacon)
}
rowWorld.ranges.merge()
if (rowWorld.ranges.size != 1) {
println("Row $y: ${rowWorld.ranges}")
for (x in 0..gridSize) {
if (rowWorld.ranges.none { x in it }) {
channel.send(x * 4000000 + y)
}
}
}
}
}
channel.receive().also { jobs.forEach { it.cancel() } }
}
}
val testInput = readInput(15, true)
// part1(testInput, 10).let { check(it == 26) { println(it) } }
// println("Test 1 passed")
part2(testInput, 20).let { check(it == 56000011) { println(it) } }
val input = readInput(15)
// println(part1(input, 2000000))
println(part2(input, 4000000))
} | 0 | Kotlin | 0 | 0 | 7eb57c9bced945dcad4750a7cc4835e56d20cbc8 | 5,208 | Advent-Of-Code | Apache License 2.0 |
src/main/kotlin/com/ginsberg/advent2021/Day07.kt | tginsberg | 432,766,033 | false | {"Kotlin": 92813} | /*
* Copyright (c) 2021 by <NAME>
*/
/**
* Advent of Code 2021, Day 7 - The Treachery of Whales
* Problem Description: http://adventofcode.com/2021/day/7
* Blog Post/Commentary: https://todd.ginsberg.com/post/advent-of-code/2021/day7/
*/
package com.ginsberg.advent2021
import kotlin.math.absoluteValue
class Day07(input: String) {
private val crabs: Map<Int, Int> = input.split(",").map { it.toInt() }.groupingBy { it }.eachCount()
fun solvePart1(): Int =
solve { it }
fun solvePart2(): Int =
solve { distance ->
(distance * (distance + 1)) / 2
}
private fun solve(fuelCost: (Int) -> Int): Int =
crabs.keys.asRange().minOf { target ->
crabs.map { (crab, crabCount) ->
fuelCost((target - crab).absoluteValue) * crabCount
}.sum()
}
private fun Set<Int>.asRange(): IntRange =
this.minOf { it }..this.maxOf { it }
}
| 0 | Kotlin | 2 | 34 | 8e57e75c4d64005c18ecab96cc54a3b397c89723 | 954 | advent-2021-kotlin | Apache License 2.0 |
2021/kotlin/src/main/kotlin/nl/sanderp/aoc/aoc2021/day25/Day25.kt | sanderploegsma | 224,286,922 | false | {"C#": 233770, "Kotlin": 126791, "F#": 110333, "Go": 70654, "Python": 64250, "Scala": 11381, "Swift": 5153, "Elixir": 2770, "Jinja": 1263, "Ruby": 1171} | package nl.sanderp.aoc.aoc2021.day25
import nl.sanderp.aoc.common.*
private typealias Grid = Map<Point2D, Char>
fun main() {
val input = readResource("Day25.txt").lines().flatMapIndexed { y, row ->
row.mapIndexed { x, c -> Point2D(x, y) to c }
}.toMap()
val width = input.maxOf { it.key.x } + 1
val height = input.maxOf { it.key.y } + 1
val steps = listOf<(Grid) -> Grid>(
{ grid -> step(grid, '>') { Point2D((it.x + 1) % width, it.y) } },
{ grid -> step(grid, 'v') { Point2D(it.x, (it.y + 1) % height) } },
)
val (answer, duration) = measureDuration<Int> {
generateSequence(input) { steps.fold(it) { state, step -> step(state) } }
.zipWithNext()
.indexOfFirst { (a, b) -> a == b } + 1
}
println("Answer: $answer (took ${duration.prettyPrint()})")
}
private fun step(state: Map<Point2D, Char>, direction: Char, stepFn: (Point2D) -> Point2D): Map<Point2D, Char> {
val next = state.toMutableMap()
for ((point, value) in state) {
val nextPoint = stepFn(point)
if (value == direction && state[nextPoint] == '.') {
next[point] = '.'
next[nextPoint] = direction
}
}
return next
} | 0 | C# | 0 | 6 | 8e96dff21c23f08dcf665c68e9f3e60db821c1e5 | 1,239 | advent-of-code | MIT License |
src/main/kotlin/com/sk/set2/279. Perfect Squares.kt | sandeep549 | 262,513,267 | false | {"Kotlin": 530613} | package com.sk.set2
class Solution279 {
fun numSquares(n: Int): Int {
val dp = IntArray(n + 1) { Int.MAX_VALUE }
dp[0] = 0
for (i in 1..n) {
var min = Int.MAX_VALUE
var j = 1
while (i - j * j >= 0) {
min = minOf(min, dp[i - j * j] + 1)
++j
}
dp[i] = min
}
return dp[n]
}
}
private fun numSquares(n: Int): Int {
val dp = IntArray(n + 1)
fun find(x: Int): Int {
if (x < 4) return x
if (dp[x] != 0) return dp[x]
var min = x
var i = 1
while (i * i <= x) {
min = minOf(min, find(x - i * i) + 1)
i++
}
dp[x] = min
return min
}
return find(n)
}
private fun numSquares2(n: Int): Int {
if (n < 4) return n
var count = n // as we can form number n with sum of atleqast n 1's.
var i = 1
while (i * i <= n) {
count = minOf(count, numSquares(n - i * i) + 1)
i++
}
return count
} | 1 | Kotlin | 0 | 0 | cf357cdaaab2609de64a0e8ee9d9b5168c69ac12 | 1,053 | leetcode-kotlin | Apache License 2.0 |
leetcode/src/linkedlist/Q206.kt | zhangweizhe | 387,808,774 | false | null | package linkedlist
import linkedlist.kt.ListNode
fun main() {
// 206. 反转链表
// https://leetcode-cn.com/problems/reverse-linked-list/
val createList = LinkedListUtil.createList(intArrayOf(1, 2, 3, 4, 5))
LinkedListUtil.printLinkedList(reverseList(createList))
}
/**
* 反转链表,返回一个新的链表
*/
fun reverseList1(head: ListNode?): ListNode? {
var cur: ListNode? = head
var newHead: ListNode? = null
while (cur != null) {
val newNode = ListNode(cur.`val`)
newNode.next = newHead
newHead = newNode
cur = cur.next
}
return newHead
}
/**
* 反转链表,在原链表上操作
*/
fun reverseListLocal(head: ListNode?): ListNode? {
var prev: ListNode? = null
var cur = head
while (cur != null) {
// 保存 cur 的后继节点
var next = cur.next
// cur 的前驱节点指向 prev
cur.next = prev
// prev 往右走一步
prev = cur
// cur 往右走一步
cur = next
}
return prev
}
private fun reverseList(head: ListNode?): ListNode? {
// https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/
if (head == null || head.next == null) {
return head
}
// 处理当前节点之后的节点
val next = reverseList(head.next)
// 处理当前节点
// 当前节点的next节点的next节点指向当前节点
head.next?.next = head
// 当前节点的 next 节点置null,否则会出现环
head.next = null
return next
} | 0 | Kotlin | 0 | 0 | 1d213b6162dd8b065d6ca06ac961c7873c65bcdc | 1,599 | kotlin-study | MIT License |
src/main/kotlin/io/github/clechasseur/adventofcode2021/Day17.kt | clechasseur | 435,726,930 | false | {"Kotlin": 315943} | package io.github.clechasseur.adventofcode2021
import io.github.clechasseur.adventofcode2021.util.Pt
import kotlin.math.max
object Day17 {
private val targetArea = object {
val x = 175..227
val y = -134..-79
}
fun part1(): Int {
val xVelocity = findXVelocity()
val highY = (10..600).mapNotNull { highestY(Pt(xVelocity, it)) }.maxByOrNull { it }
require(highY != null) { "No dice" }
return highY
}
fun part2(): Int = (-300..600).flatMap { yVelocity ->
(1..300).mapNotNull { xVelocity ->
highestY(Pt(xVelocity, yVelocity))
}
}.count()
private fun `fire!`(initialVelocity: Pt): Sequence<Pt> = sequence {
var pt = Pt.ZERO
yield(pt)
var velocity = initialVelocity
while (true) {
pt += velocity
val drift = Pt(when {
velocity.x > 0 -> -1
velocity.x < 0 -> 1
else -> 0
}, -1)
velocity += drift
yield(pt)
}
}
private fun highestY(velocity: Pt): Int? {
val it = `fire!`(velocity).iterator()
var pt = it.next()
var high = pt.y
while ((pt.x !in targetArea.x || pt.y !in targetArea.y) && pt.y >= targetArea.y.first) {
pt = it.next()
high = max(high, pt.y)
}
return if (pt.x in targetArea.x && pt.y in targetArea.y) high else null
}
private fun findXVelocity(): Int {
var xVelocity = 0
var x = 0
while (x !in targetArea.x) {
x += xVelocity
xVelocity += 1
}
return xVelocity
}
}
| 0 | Kotlin | 0 | 0 | 4b893c001efec7d11a326888a9a98ec03241d331 | 1,681 | adventofcode2021 | MIT License |
year2019/day14/part2/src/main/kotlin/com/curtislb/adventofcode/year2019/day14/part2/Year2019Day14Part2.kt | curtislb | 226,797,689 | false | {"Kotlin": 2146738} | /*
--- Part Two ---
After collecting ORE for a while, you check your cargo hold: 1 trillion (1000000000000) units of
ORE.
With that much ore, given the examples above:
- The 13312 ORE-per-FUEL example could produce 82892753 FUEL.
- The 180697 ORE-per-FUEL example could produce 5586022 FUEL.
- The 2210736 ORE-per-FUEL example could produce 460664 FUEL.
Given 1 trillion ORE, what is the maximum amount of FUEL you can produce?
*/
package com.curtislb.adventofcode.year2019.day14.part2
import com.curtislb.adventofcode.common.search.bisect
import com.curtislb.adventofcode.year2019.day14.chemistry.MaterialAmount
import com.curtislb.adventofcode.year2019.day14.chemistry.Nanofactory
import java.nio.file.Path
import java.nio.file.Paths
/**
* Returns the solution to the puzzle for 2019, day 14, part 2.
*
* @param inputPath The path to the input file for this puzzle.
* @param rawMaterial The name of an available raw material that can be used for reactions.
* @param rawMaterialAvailableAmount The amount of raw material that is available for reactions.
* @param desiredMaterial The name of the material that should ultimately be produced.
*/
fun solve(
inputPath: Path = Paths.get("..", "input", "input.txt"),
rawMaterial: String = "ORE",
rawMaterialAvailableAmount: Long = 1_000_000_000_000L,
desiredMaterial: String = "FUEL"
): Long {
val factory = Nanofactory(inputPath.toFile())
// Binary search for the first product amount requiring more raw material than available
val rawMaterials = setOf(rawMaterial)
val productAmountLimit = bisect { amount ->
val products = listOf(MaterialAmount(desiredMaterial, amount))
val requiredMaterials = factory.findRequiredMaterials(rawMaterials, products)
val rawMaterialNeeded =
requiredMaterials?.find { (material, _) -> material == rawMaterial }?.amount
?: error("Failed to produce $desiredMaterial during bisect")
rawMaterialNeeded > rawMaterialAvailableAmount
}
return productAmountLimit - 1L
}
fun main() {
println(solve())
}
| 0 | Kotlin | 1 | 1 | 6b64c9eb181fab97bc518ac78e14cd586d64499e | 2,094 | AdventOfCode | MIT License |
src/main/aoc2023/Day6.kt | nibarius | 154,152,607 | false | {"Kotlin": 963896} | package aoc2023
class Day6(input: List<String>) {
private data class Race(val time: Int, val distance: Long)
private val races: List<Race>
private val race2: Race
init {
races = buildList {
val times = input.first().substringAfter(":").trim().split("\\s+".toRegex())
val distance = input.last().substringAfter(":").trim().split("\\s+".toRegex())
for (i in times.indices) {
add(Race(times[i].toInt(), distance[i].toLong()))
}
race2 = Race(
times.joinToString("").toInt(),
distance.joinToString("").toLong()
)
}
}
fun distance(holdTime: Int, totalTime: Int) = (totalTime - holdTime).toLong() * holdTime.toLong()
fun solvePart1(): Int {
return races.map { race ->
(1..<race.time).map { distance(it, race.time) }.filter { it > race.distance }
}.map { it.size }.reduce(Int::times)
}
fun solvePart2(): Int {
val firstWinningTime = (1..<race2.time).first { distance(it, race2.time) > race2.distance }
val lastWinningTime = (1..<race2.time).reversed().first { distance(it, race2.time) > race2.distance }
return lastWinningTime - firstWinningTime + 1
}
} | 0 | Kotlin | 0 | 6 | f2ca41fba7f7ccf4e37a7a9f2283b74e67db9f22 | 1,280 | aoc | MIT License |
src/main/java/challenges/coderbyte/StringReduction.kt | ShabanKamell | 342,007,920 | false | null | package challenges.coderbyte
/*
Have the function StringReduction(str) take the str parameter being passed and return the smallest
number you can get through the following reduction method. The method is: Only the letters a, b, and c
will be given in str and you must take two different adjacent characters and replace it with the third.
For example "ac" can be replaced with "b" but "aa" cannot be replaced with anything.
This method is done repeatedly until the string cannot be further reduced,
and the length of the resulting string is to be outputted.
For example: if str is "cab", then "ca" can be reduced to "b" and you get "bb" (you can also reduce it to "cc").
The reduction is done so the output should be 2. If str is
"bcab", "bc" reduces to "a", so you have "aab", then "ab" reduces to "c", and the final string "ac"
is reduced to "b" so the output should be 1.
*/
object StringReduction {
private fun stringReduction(str: String): String {
val sum = 'a'.toInt() + 'b'.toInt() + 'c'.toInt()
return reduce(str, sum).length.toString()
}
private fun reduce(str: String, sum: Int): String {
if (str.length == 1) return str
var result = ""
var i = 0
val length = str.length
while (i < length) {
val current = str[i]
if (i + 1 < length && current != str[i + 1]) {
val new = sum - current.toInt() - str[i + 1].toInt()
result += new.toChar()
i += 2
continue
}
result += current
i++
}
// if the result is equal to str, this means all chars are equal
// So we don't need further processing
if (result == str) return str
return reduce(result, sum)
}
@JvmStatic
fun main(args: Array<String>) {
println(stringReduction("abcabc")) // 2
println(stringReduction("cccc")) // 4
}
} | 0 | Kotlin | 0 | 0 | ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70 | 1,950 | CodingChallenges | Apache License 2.0 |
src/main/kotlin/tr/emreone/kotlin_utils/data_structures/GraphSearch.kt | EmRe-One | 442,916,831 | false | {"Kotlin": 173543} | package tr.emreone.kotlin_utils.data_structures
import java.util.*
import kotlin.collections.ArrayDeque
enum class SearchControl { STOP, CONTINUE }
typealias DebugHandler<N> = (level: Int, nodesOnLevel: Collection<N>, nodesVisited: Collection<N>) -> SearchControl
typealias SolutionPredicate<N> = (node: N) -> Boolean
data class SearchResult<N>(val currentNode: N?, val distance: Map<N, Int>, val prev: Map<N, N>) {
val distanceToStart: Int? = currentNode?.let { distance[it] }
val steps: Int? by lazy { (path.size - 1).takeIf { it >= 0 } }
val path by lazy { buildPath() }
private fun buildPath(): List<N> {
val path = ArrayDeque<N>()
if (currentNode in distance) {
var nodeFoundThroughPrevious: N? = currentNode
while (nodeFoundThroughPrevious != null) {
path.addFirst(nodeFoundThroughPrevious)
nodeFoundThroughPrevious = prev[nodeFoundThroughPrevious]
}
}
return path
}
}
class AStarSearch<N>(
vararg startNodes: N,
val neighborNodes: (N) -> Collection<N>,
val cost: (N, N) -> Int,
val costEstimation: (N, N) -> Int,
val onExpand: ((SearchResult<N>) -> Unit)? = null,
) {
private val dist = HashMap<N, Int>().apply { startNodes.forEach { put(it, 0) } }
private val prev = HashMap<N, N>()
private val openList = minPriorityQueueOf(elements = startNodes)
private val closedList = HashSet<N>()
fun search(destNode: N, limitSteps: Int? = null): SearchResult<N> {
fun expandNode(currentNode: N) {
onExpand?.invoke(SearchResult(currentNode, dist, prev))
for (successor in neighborNodes(currentNode)) {
if (successor in closedList)
continue
val tentativeDist = dist[currentNode]!! + cost(currentNode, successor)
if (successor in openList && tentativeDist >= dist[successor]!!)
continue
prev[successor] = currentNode
dist[successor] = tentativeDist
val f = tentativeDist + costEstimation(successor, destNode)
openList.insertOrUpdate(successor, f)
}
}
if (destNode in dist)
return SearchResult(destNode, dist, prev)
var steps = 0
while (steps++ != limitSteps && openList.isNotEmpty()) {
val currentNode = openList.extractMin()
if (currentNode == destNode)
return SearchResult(destNode, dist, prev)
closedList += currentNode
expandNode(currentNode)
}
return SearchResult(openList.peekOrNull(), dist, prev)
}
}
class Dijkstra<N>(
val startNode: N,
val neighborNodes: (N) -> Collection<N>,
val cost: (N, N) -> Int,
) {
private val dist = HashMap<N, Int>().apply { put(startNode, 0) }
private val prev = HashMap<N, N>()
private val queue = minPriorityQueueOf(startNode to 0)
fun search(predicate: SolutionPredicate<N>): SearchResult<N> {
while (queue.isNotEmpty()) {
val u = queue.extractMin()
if (predicate(u)) {
return SearchResult(u, dist, prev)
}
for (v in neighborNodes(u)) {
val alt = dist[u]!! + cost(u, v)
if (alt < dist.getOrDefault(v, Int.MAX_VALUE)) {
dist[v] = alt
prev[v] = u
queue.insertOrUpdate(v, alt)
}
}
}
// failed search
return SearchResult(null, dist, prev)
}
}
//class DepthSearch<N, E>(
// val startNode: N,
// private val edgesOfNode: (N) -> Iterable<E>,
// private val walkEdge: (N, E) -> N,
//) {
// private val nodesVisited = mutableSetOf<N>(startNode)
// private val nodesDiscoveredThrough = mutableMapOf<N, N>()
//
// fun search(predicate: SolutionPredicate<N>): SearchResult<N> {
// if (predicate(startNode))
// return SearchResult(startNode, emptyMap(), nodesDiscoveredThrough)
//
// val edges = edgesOfNode(startNode)
// for (edge in edges) {
// val nextNode = walkEdge(node, edge)
// if (!nodesVisited.contains(nextNode)) {
// nodesDiscoveredThrough[nextNode] = node
// val found = searchFrom(nextNode, isSolution)
// if (found != null)
// return found
// }
// }
// return null
// }
//}
interface EdgeGraph<N, E> {
fun edgesOfNode(node: N): Iterable<E>
fun walkEdge(node: N, edge: E): N
}
abstract class UninformedSearch<N, E>(val graph: EdgeGraph<N, E>) : EdgeGraph<N, E> by graph {
data class Result<N, E>(val node: N, val prev: Map<N, Pair<N, E>>, val visited: Set<N>)
fun search(start: N, destination: N) = search(start) { it == destination }
open fun search(start: N, solutionPredicate: SolutionPredicate<N>): Result<N, E>? =
traverse(start).firstOrNull { solutionPredicate(it.node) }
abstract fun traverse(start: N): Sequence<Result<N, E>>
class BFS<N, E>(graph: EdgeGraph<N, E>) : UninformedSearch<N, E>(graph) {
override fun traverse(start: N): Sequence<Result<N, E>> = sequence {
val nodesVisited = HashSet<N>()
val nodesDiscoveredThrough = HashMap<N, Pair<N, E>>()
val queue = ArrayDeque<N>()
queue += start
nodesVisited += start
yield(Result(start, nodesDiscoveredThrough, nodesVisited))
while (queue.isNotEmpty()) {
val currentNode = queue.removeFirst()
nodesVisited += currentNode
edgesOfNode(currentNode).forEach { edge ->
val neighbor = walkEdge(currentNode, edge)
if (neighbor !in nodesVisited) {
nodesDiscoveredThrough[neighbor] = currentNode to edge
queue.addLast(neighbor)
yield(Result(neighbor, nodesDiscoveredThrough, nodesVisited))
}
}
}
}
}
}
fun <N, E> SearchEngineWithEdges<N, E>.bfsSequence(startNode: N): Sequence<N> = sequence {
val nodesVisited = mutableSetOf<N>()
val nodesDiscoveredThrough = mutableMapOf<N, N>()
val queue = ArrayDeque<N>()
queue += startNode
yield(startNode)
while (queue.isNotEmpty()) {
val currentNode = queue.removeFirst()
nodesVisited += currentNode
edgesOfNode(currentNode).forEach { edge ->
val neighbor = walkEdge(currentNode, edge)
if (neighbor !in nodesVisited) {
nodesDiscoveredThrough[neighbor] = currentNode
queue.addLast(neighbor)
yield(neighbor)
}
}
}
}
open class SearchEngineWithEdges<N, E>(
val edgesOfNode: (N) -> Iterable<E>,
val walkEdge: (N, E) -> N,
) {
var debugHandler: DebugHandler<N>? = null
inner class BfsSearch(val startNode: N, val isSolution: SolutionPredicate<N>) {
val solution: N?
val nodesVisited = mutableSetOf<N>()
val nodesDiscoveredThrough = mutableMapOf<N, N>()
private tailrec fun searchLevel(nodesOnLevel: Set<N>, level: Int = 0): N? {
if (debugHandler?.invoke(level, nodesOnLevel, nodesVisited) == SearchControl.STOP)
return null
val nodesOnNextLevel = mutableSetOf<N>()
nodesOnLevel.forEach { currentNode ->
nodesVisited.add(currentNode)
edgesOfNode(currentNode).forEach { edge ->
val node = walkEdge(currentNode, edge)
if (node !in nodesVisited && node !in nodesOnLevel) {
nodesDiscoveredThrough[node] = currentNode
if (isSolution(node))
return node
else
nodesOnNextLevel.add(node)
}
}
}
return if (nodesOnNextLevel.isEmpty())
null
else
searchLevel(nodesOnNextLevel, level + 1)
}
private fun buildStack(node: N?): List<N> {
//println("Building stack for solution node $node")
val pathStack = ArrayDeque<N>()
var nodeFoundThroughPrevious = node
while (nodeFoundThroughPrevious != null) {
pathStack.addFirst(nodeFoundThroughPrevious)
nodeFoundThroughPrevious = nodesDiscoveredThrough[nodeFoundThroughPrevious]
}
return pathStack
}
init {
solution = if (isSolution(startNode)) startNode else searchLevel(setOf(startNode))
}
fun path(): List<N> {
return buildStack(solution)
}
}
private inner class DepthSearch(val startNode: N, val isSolution: SolutionPredicate<N>) {
private val nodesVisited = mutableSetOf<N>()
private val nodesDiscoveredThrough = mutableMapOf<N, N>()
private fun searchFrom(node: N, isSolution: SolutionPredicate<N>): N? {
if (isSolution(node))
return node
nodesVisited.add(node)
val edges = edgesOfNode(node)
for (edge in edges) {
val nextNode = walkEdge(node, edge)
if (!nodesVisited.contains(nextNode)) {
nodesDiscoveredThrough[nextNode] = node
val found = searchFrom(nextNode, isSolution)
if (found != null)
return found
}
}
return null
}
private fun buildStack(node: N?): Stack<N> {
//println("Building stack for solution node $node")
val pathStack = Stack<N>()
var nodeFoundThroughPrevious = node
while (nodeFoundThroughPrevious != null) {
pathStack.add(0, nodeFoundThroughPrevious)
nodeFoundThroughPrevious = nodesDiscoveredThrough[nodeFoundThroughPrevious]
}
return pathStack
}
fun search() = buildStack(searchFrom(startNode, isSolution))
fun findBest(): Pair<Stack<N>, Set<N>> {
return buildStack(searchFrom(startNode, isSolution)) to nodesVisited
}
}
fun bfsSearch(startNode: N, isSolution: SolutionPredicate<N>) =
BfsSearch(startNode, isSolution)
fun depthFirstSearch(startNode: N, isSolution: SolutionPredicate<N>): Stack<N> {
return DepthSearch(startNode, isSolution).search()
}
fun depthFirstSearchWithNodes(startNode: N, isSolution: SolutionPredicate<N>): Pair<Stack<N>, Set<N>> {
return DepthSearch(startNode, isSolution).findBest()
}
fun completeAcyclicTraverse(startNode: N): Sequence<AcyclicTraverseLevel<N>> =
sequence {
var nodesOnPreviousLevel: Set<N>
var nodesOnLevel = setOf<N>()
var nodesOnNextLevel = setOf(startNode)
var level = 0
while (nodesOnNextLevel.isNotEmpty()) {
nodesOnPreviousLevel = nodesOnLevel
nodesOnLevel = nodesOnNextLevel
yield(AcyclicTraverseLevel(level++, nodesOnLevel, nodesOnPreviousLevel))
nodesOnNextLevel = mutableSetOf()
nodesOnLevel.forEach { node ->
nodesOnNextLevel.addAll(
edgesOfNode(node).map { e -> walkEdge(node, e) }
.filter { neighbor ->
neighbor !in nodesOnLevel && neighbor !in nodesOnPreviousLevel
}
)
}
}
}
}
data class AcyclicTraverseLevel<N>(val level: Int, val nodesOnLevel: Set<N>, val nodesOnPreviousLevel: Set<N>) :
Collection<N> by nodesOnLevel
data class SearchLevel<N>(val level: Int, val nodesOnLevel: Collection<N>, val visited: Set<N>)
class SearchEngineWithNodes<N>(neighborNodes: (N) -> Collection<N>) :
SearchEngineWithEdges<N, N>(neighborNodes, { _, edge -> edge })
fun <N, E> breadthFirstSearch(
startNode: N,
edgesOf: (N) -> Collection<E>,
walkEdge: (N, E) -> N,
isSolution: SolutionPredicate<N>,
) =
SearchEngineWithEdges(edgesOf, walkEdge).bfsSearch(startNode, isSolution)
fun <N> breadthFirstSearch(
startNode: N,
neighborNodes: (N) -> Collection<N>,
isSolution: SolutionPredicate<N>,
) =
SearchEngineWithNodes(neighborNodes).bfsSearch(startNode, isSolution)
fun <N> depthFirstSearch(
startNode: N,
neighborNodes: (N) -> Collection<N>,
isSolution: SolutionPredicate<N>,
): Stack<N> =
SearchEngineWithNodes(neighborNodes).depthFirstSearch(startNode, isSolution)
fun <N> loggingDebugger(): DebugHandler<N> = { level: Int, nodesOnLevel: Collection<N>, nodesVisited: Collection<N> ->
println("I am on level $level, searching through ${nodesOnLevel.size}. Visited so far: ${nodesVisited.size}")
SearchControl.CONTINUE
}
| 0 | Kotlin | 0 | 0 | aee38364ca1827666949557acb15ae3ea21881a1 | 13,142 | kotlin-utils | Apache License 2.0 |
src/Day01.kt | rinas-ink | 572,920,513 | false | {"Kotlin": 14483} | fun main() {
fun getSetOfElves(input: List<String>): List<Int> {
val elves = mutableListOf<Int>();
var last = 0
for (i in input) {
try {
last += i.toInt()
} catch (_: NumberFormatException) {
elves.add(last)
last = 0
}
}
if (last != 0) elves.add(last)
return elves.sortedDescending()
}
fun part1(input: List<String>) = getSetOfElves(input).max()
fun part2(input: List<String>): Int {
val elves = getSetOfElves(input)
return elves[0] + elves[1] + elves[2]
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day01_test")
// check(part1(testInput) == 24000)
//check(part2(testInput) == 45000)
val input = readInput("Day01")
println(part1(testInput))
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 462bcba7779f7bfc9a109d886af8f722ec14c485 | 945 | anvent-kotlin | Apache License 2.0 |
src/Day08.kt | RickShaa | 572,623,247 | false | {"Kotlin": 34294} | import java.util.*
import kotlin.collections.ArrayDeque
import kotlin.math.sign
fun main() {
val fileName = "day08.txt"
val testFileName = "day08_test.txt"
val input = FileUtil.getListOfLines(fileName);
val trees = input.map { it -> it.toCharArray().map { it.toString().toInt() } }
//PART1
fun List<List<Int>>.countEdges():Int{
val sideA = this.size
val sideB = this[0].size - 2
return sideA * 2 + sideB * 2
}
fun currentTree(posY:Int, posX:Int):Int{
return trees[posY][posX]
}
fun treeIsVisibleFromAbove(posY:Int, posX:Int):Boolean{
val tree = currentTree(posY,posX)
//always go from edge to current tree position if there is one tree that is bigger it is not visible anymore
for(y in 0 until posY){
if(trees[y][posX] >= tree){
return false
}
}
return true;
}
fun treeIsVisibleFromBelow(posY:Int, posX:Int):Boolean{
val tree = currentTree(posY,posX)
for(y in (trees.size -1) downTo (posY + 1) ){
if(trees[y][posX] >= tree){
return false
}
}
return true;
}
fun isTreeVisibleInColumn(posY:Int, posX:Int):Boolean{
return treeIsVisibleFromAbove(posY,posX) || treeIsVisibleFromBelow(posY,posX)
}
fun isTreeVisibleToLeft(posY:Int, posX:Int):Boolean{
val tree = currentTree(posY,posX)
val rowOfTrees = trees[posY]
for(x in 0 until posX){
if(rowOfTrees[x] >= tree){
return false
}
}
return true;
}
fun isTreeVisibleToRight(posY:Int, posX:Int):Boolean{
val tree = currentTree(posY,posX)
val rowOfTrees = trees[posY]
for(x in (rowOfTrees.size -1) downTo (posX + 1)){
if(rowOfTrees[x] >= tree){
return false
}
}
return true;
}
fun isTreeVisibleInRow(posY:Int, posX:Int):Boolean{
// scans left and right
return isTreeVisibleToLeft(posY, posX) || isTreeVisibleToRight(posY,posX)
}
fun getNumberOfVisibleTrees(trees:List<List<Int>>):Int{
val edgeTrees = trees.countEdges()
var visibleTrees = edgeTrees;
//skip first and last row because it is already visible
for(y in 1 until trees.size - 1){
for (x in 1 until trees[y].size -1){
if(isTreeVisibleInColumn(y,x) || isTreeVisibleInRow(y,x)){
visibleTrees++
}
}
}
return visibleTrees
}
//PART 2
fun getViewingDistanceAbove(posY:Int, posX:Int):Int{
val tree = currentTree(posY,posX)
var distance = 0;
if(posY - 1 > 0){
for(y in (posY -1) downTo 0){
if(trees[y][posX] < tree){
distance++
}else{
distance++
return distance
}
}
}
return distance;
}
fun getViewingDistanceFromBelow(posY:Int, posX:Int):Int{
val tree = currentTree(posY,posX)
var distance = 0;
if(posY + 1 < trees.size){
for(y in (posY + 1) until trees.size){
if(trees[y][posX] < tree){
distance++
}else{
distance++
return distance
}
}
}
return distance;
}
fun getViewingDistanceLeft(posY:Int, posX:Int):Int{
val tree = currentTree(posY,posX)
var distance = 0;
if((posX-1) > 0){
for(x in (posX-1) downTo 0){
if(trees[posY][x] < tree){
distance++
}else{
distance++
return distance
}
}
}
return distance;
}
fun getViewingDistanceRight(posY:Int, posX:Int):Int{
val tree = currentTree(posY,posX)
val rowOfTrees = trees[posY]
var distance = 0;
if(posX +1 < rowOfTrees.size){
for(x in (posX +1) until rowOfTrees.size){
if(trees[posY][x] < tree){
distance++
}else{
distance++
return distance
}
}
}
return distance;
}
val scenicScores = mutableListOf<Int>()
fun getScenicScores(trees:List<List<Int>>){
for(y in trees.indices){
for (x in 0 until trees[y].size){
var score = getViewingDistanceAbove(y,x) *
getViewingDistanceFromBelow(y,x) *
getViewingDistanceLeft(y,x) *
getViewingDistanceRight(y,x)
scenicScores.add(score)
}
}
}
getScenicScores(trees)
val bestScenicScore = scenicScores.max()
println(scenicScores)
println(bestScenicScore)
}
| 0 | Kotlin | 0 | 1 | 76257b971649e656c1be6436f8cb70b80d5c992b | 5,061 | aoc | Apache License 2.0 |
src/main/kotlin/ru/timakden/aoc/year2015/Day11.kt | timakden | 76,895,831 | false | {"Kotlin": 321649} | package ru.timakden.aoc.year2015
import ru.timakden.aoc.util.measure
import ru.timakden.aoc.util.readInput
/**
* [Day 11: Corporate Policy](https://adventofcode.com/2015/day/11).
*/
object Day11 {
@JvmStatic
fun main(args: Array<String>) {
measure {
val input = readInput("year2015/Day11").single()
var newPassword = solve(input)
println("Part One: $newPassword")
newPassword = solve(newPassword)
println("Part Two: $newPassword")
}
}
fun solve(input: String): String {
var newPassword = incrementPassword(input)
while (!checkPassword(newPassword)) newPassword = incrementPassword(newPassword)
return newPassword
}
fun checkPassword(password: String): Boolean {
val charArray = password.toCharArray()
val firstRequirement = charArray.indices.any {
it + 2 <= charArray.lastIndex &&
charArray[it + 1] == charArray[it] + 1 &&
charArray[it + 2] == charArray[it] + 2
}
val secondRequirement = "[^iol]".toRegex().containsMatchIn(password)
val thirdRequirement = "(.)\\1.*(.)\\2".toRegex().containsMatchIn(password)
return firstRequirement && secondRequirement && thirdRequirement
}
private fun incrementPassword(oldPassword: String): String {
val charArray = oldPassword.toCharArray()
var startIndex = charArray.lastIndex
while (charArray[startIndex] == 'z') startIndex--
(startIndex..charArray.lastIndex).forEach {
charArray[it] = charArray[it] + 1
if (!charArray[it].isLetter()) charArray[it] = 'a'
}
return String(charArray)
}
}
| 0 | Kotlin | 0 | 3 | acc4dceb69350c04f6ae42fc50315745f728cce1 | 1,750 | advent-of-code | MIT License |
src/main/kotlin/d7_TheTreacheryOfWhales/TheTreacheryOfWhales.kt | aormsby | 425,644,961 | false | {"Kotlin": 68415} | package d7_TheTreacheryOfWhales
import util.Input
import util.Output
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.roundToInt
fun main() {
Output.day(7, "The Treachery of Whales")
val startTime = Output.startTime()
val crabmarines = Input.parseToListOf<Int>(
rawData = Input.parseAllText("/input/d7_crabmarine_positions.txt"), delimiter = ","
)
val median = crabmarines.sorted().median()
val fuelToMedian = crabmarines.sumOf { abs(it - median) }
Output.part(1, "Fuel to Align to Median with 'Single Step' Consumption", fuelToMedian)
val averageFloor = crabmarines.average().toInt() // check lower
val averageCiel = crabmarines.average().roundToInt() // possibly check upper
val fuelToAverageFloor = crabmarines.sumToAverage(averageFloor)
val fuelToAverage = if (averageFloor != averageCiel)
min(fuelToAverageFloor, crabmarines.sumToAverage(averageCiel))
else fuelToAverageFloor
Output.part(2, "Fuel to Align to Average with 'Sum of Integers' Consumption", fuelToAverage)
Output.executionTime(startTime)
}
fun List<Int>.median(): Int =
if (this.size % 2 == 0)
(this[this.size / 2] + this[(this.size - 1) / 2]) / 2
else this[this.size / 2]
// with higher fuel cost
fun List<Int>.sumToAverage(ave: Int) =
this.sumOf {
val diff = abs(it - ave)
diff * (1 + diff) / 2
} | 0 | Kotlin | 1 | 1 | 193d7b47085c3e84a1f24b11177206e82110bfad | 1,414 | advent-of-code-2021 | MIT License |
src/main/kotlin/aoc/Graph.kt | w8mr | 572,700,604 | false | {"Kotlin": 140954} | package aoc
import java.util.*
interface GraphNode<T> {
val neighbours: List<Pair<Int, GraphNode<T>>>
val value: T
}
fun <T> findShortestPaths(node: GraphNode<T>): MutableMap<GraphNode<T>, Pair<Int, GraphNode<T>?>> {
val shortestPaths = mutableMapOf<GraphNode<T>, Pair<Int, GraphNode<T>?>>()
val toInspect =
PriorityQueue<GraphNode<T>> { n1, n2 -> shortestPaths[n1]!!.first - shortestPaths[n2]!!.first }
val inspected = mutableSetOf<GraphNode<T>>()
shortestPaths[node] = 0 to null
toInspect.add(node)
while (toInspect.isNotEmpty()) {
val inspect = toInspect.remove()
val pathLength = shortestPaths[inspect]!!.first
inspect.neighbours.forEach() { (weight, neighbour) ->
if (!inspected.contains(neighbour)) {
val newLength = pathLength + weight
if (newLength < (shortestPaths[neighbour]?.first ?: Int.MAX_VALUE)) {
shortestPaths[neighbour] = newLength to inspect
toInspect.remove(neighbour)
toInspect.add(neighbour)
}
}
}
inspected.add(inspect)
}
return shortestPaths
}
fun <T> findShortestPath(startNode: GraphNode<T>, endNode: (GraphNode<T>) -> Boolean): Int? {
val shortestPaths = findShortestPaths(startNode)
val key = shortestPaths.keys.find(endNode)
return shortestPaths[key]?.first
}
| 0 | Kotlin | 0 | 0 | e9bd07770ccf8949f718a02db8d09daf5804273d | 1,429 | aoc-kotlin | Apache License 2.0 |
src/main/kotlin/Day05.kt | AlmazKo | 576,500,782 | false | {"Kotlin": 26733} | import java.util.Deque
import java.util.LinkedList
import java.util.SortedMap
import java.util.TreeMap
object Day05 : Task {
@JvmStatic
fun main(args: Array<String>) = execute()
override fun part1(input: Iterable<String>): Any {
val stacks = parseCrates(input)
parseCommands(input).forEach { (size, from, to) ->
move(stacks[from]!!, stacks[to]!!, size)
}
return stacks.top()
}
override fun part2(input: Iterable<String>): Any {
val stacks = parseCrates(input)
parseCommands(input).forEach { (size, from, to) ->
move2(stacks[from]!!, stacks[to]!!, size)
}
return stacks.top()
}
private fun move(from: Deque<Char>, to: Deque<Char>, size: Int) {
repeat(size) {
to.push(from.poll()!!)
}
}
private fun move2(from: Deque<Char>, to: Deque<Char>, size: Int) {
LinkedList<Char>().apply {
repeat(size) { push(from.poll()) }
repeat(size) { to.push(poll()) }
}
}
data class Command(
val size: Int,
val from: Int,
val to: Int
)
// --- util
private fun parseCommands(input: Iterable<String>): Sequence<Command> {
return input.asSequence()
.filter { it.startsWith('m') }
.map { it.toCommand() }
}
private fun parseCrates(input: Iterable<String>): SortedMap<Int, Deque<Char>> {
val crates = TreeMap<Int, Deque<Char>>()
input.takeWhile(String::isNotEmpty)
.forEach {
it.forEachIndexed { i, char ->
if (char in 'A'..'Z') {
crates.getOrPut((i + 1) / 4 + 1, ::LinkedList).add(char)
}
}
}
return crates
}
private fun SortedMap<Int, Deque<Char>>.top(): String {
return values.map { it.peek() }.joinToString("")
}
private fun String.toCommand(): Command {
val chunks = split(' ')
return Command(chunks[1].toInt(), chunks[3].toInt(), chunks[5].toInt())
}
} | 0 | Kotlin | 0 | 1 | 109cb10927328ce296a6b0a3600edbc6e7f0dc9f | 2,112 | advent2022 | MIT License |
src/main/kotlin/de/mbdevelopment/adventofcode/year2021/solvers/day3/Day3Puzzle2.kt | Any1s | 433,954,562 | false | {"Kotlin": 96683} | package de.mbdevelopment.adventofcode.year2021.solvers.day3
import de.mbdevelopment.adventofcode.year2021.solvers.PuzzleSolver
class Day3Puzzle2 : PuzzleSolver {
override fun solve(inputLines: Sequence<String>) = lifeSupportRating(inputLines).toString();
private fun lifeSupportRating(diagnosticReport: Sequence<String>): Int {
val readings = diagnosticReport
.map { it.toCharArray() }
.map { it.map { digit -> digit.digitToInt() } }
.toList()
val oxygenGeneratorRating = readings.filterBySignificantBitSelector({ if (it >= 0) 1 else 0 })
.bitVectorToInt()
val co2ScrubberRating = readings.filterBySignificantBitSelector({ if (it >= 0) 0 else 1 })
.bitVectorToInt()
return oxygenGeneratorRating * co2ScrubberRating
}
private fun List<List<Int>>.filterBySignificantBitSelector(
bitIndexSumToSignificantBit: (Int) -> Int,
index: Int = 0
): List<Int> {
return if (size == 1 || index == first().size) {
single()
} else {
val selectionBit = map { it[index] }
.map { if(it == 1) 1 else -1 }
.reduce(Int::plus)
.run(bitIndexSumToSignificantBit)
filter { it[index] == selectionBit }.filterBySignificantBitSelector(bitIndexSumToSignificantBit, index + 1)
}
}
private fun List<Int>.bitVectorToInt() = joinToString("").toInt(2)
} | 0 | Kotlin | 0 | 0 | 21d3a0e69d39a643ca1fe22771099144e580f30e | 1,472 | AdventOfCode2021 | Apache License 2.0 |
src/main/kotlin/at/mpichler/aoc/solutions/year2021/Day04.kt | mpichler94 | 656,873,940 | false | {"Kotlin": 196457} | package at.mpichler.aoc.solutions.year2021
import at.mpichler.aoc.lib.Day
import at.mpichler.aoc.lib.PartSolution
import org.jetbrains.kotlinx.multik.api.mk
import org.jetbrains.kotlinx.multik.api.zeros
import org.jetbrains.kotlinx.multik.ndarray.data.D2Array
import org.jetbrains.kotlinx.multik.ndarray.data.get
import org.jetbrains.kotlinx.multik.ndarray.data.set
import org.jetbrains.kotlinx.multik.ndarray.operations.any
import org.jetbrains.kotlinx.multik.ndarray.operations.map
import org.jetbrains.kotlinx.multik.ndarray.operations.mapMultiIndexed
import org.jetbrains.kotlinx.multik.ndarray.operations.plusAssign
open class Part4A : PartSolution() {
lateinit var numbers: List<Int>
lateinit var boards: List<D2Array<Int>>
override fun parseInput(text: String) {
val lines = text.trimEnd().split("\n")
numbers = lines.first().split(',').map { it.toInt() }
val boards = mutableListOf<D2Array<Int>>()
var board = mk.zeros<Int>(5, 5)
var y = 0
for (boardId in 2..<lines.size) {
val line = lines[boardId]
if (line == "") {
y = 0
boards.add(board)
board = mk.zeros<Int>(5, 5)
continue
}
val row = line.trim().split(Regex(" +"))
for (x in row.indices) {
board[x, y] = row[x].toInt()
}
y += 1
}
boards.add(board)
this.boards = boards
}
override fun compute(): Int {
val marks = List(boards.size) { mk.zeros<Int>(5, 5) }
for (num in numbers) {
markNumber(num, boards, marks)
val idx = checkWin(marks)
if (idx >= 0) {
return computeScore(num, boards[idx], marks[idx])
}
}
error("No winning score found")
}
fun markNumber(number: Int, boards: List<D2Array<Int>>, marks: List<D2Array<Int>>) {
for (i in boards.indices) {
val indices = boards[i].map { if (it == number) 1 else 0 }
marks[i] += indices
}
}
fun checkWin(marks: List<D2Array<Int>>): Int {
for (i in marks.indices) {
val boardMarks = marks[i]
val rowSums = mk.math.sumD2(boardMarks, 1)
val columnSums = mk.math.sumD2(boardMarks, 0)
if (rowSums.any { it > 4 } || columnSums.any { it > 4 }) {
return i
}
}
return -1
}
fun computeScore(number: Int, board: D2Array<Int>, marks: D2Array<Int>): Int {
val score = mk.math.sum(board.mapMultiIndexed { index, it -> if (marks[index[0], index[1]] == 0) it else 0 })
return score * number
}
override fun getExampleAnswer(): Int {
return 4512
}
}
class Part4B : Part4A() {
override fun compute(): Int {
val marks = MutableList(boards.size) { mk.zeros<Int>(5, 5) }
val boards = this.boards.toMutableList()
var lastBoard = mk.zeros<Int>(5, 5)
var lastMarks = mk.zeros<Int>(5, 5)
var lastNum = 0
for (num in numbers) {
markNumber(num, boards, marks)
var idx = checkWin(marks)
if (boards.size == 1 && idx >= 0) {
return computeScore(num, boards[0], marks[0])
}
while (idx >= 0) {
lastBoard = boards[idx]
lastMarks = marks[idx]
lastNum = num
boards.removeAt(idx)
marks.removeAt(idx)
idx = checkWin(marks)
}
}
if (boards.size > 1) {
return computeScore(lastNum, lastBoard, lastMarks)
}
error("No winning score found")
}
override fun getExampleAnswer(): Int {
return 1924
}
}
fun main() {
Day(2021, 4, Part4A(), Part4B())
} | 0 | Kotlin | 0 | 0 | 69a0748ed640cf80301d8d93f25fb23cc367819c | 3,885 | advent-of-code-kotlin | MIT License |
src/Day03.kt | jgodort | 573,181,128 | false | null | const val LOWERCASE_DIFFERENCE = 96
const val UPPERCASE_DIFFERENCE = 38
fun main() {
val inputData = readInput("Day3_input")
println(day3Part1(inputData))
println(day3Part2(inputData))
}
fun day3Part1(input: String): Int = input.lines().map { line ->
val content = line.toList()
val rucksacks = content.chunked(content.size / 2)
rucksacks[0]
.intersect(other = rucksacks[1].toSet())
.first()
}.sumOf { convertToScore(it) }
fun day3Part2(input: String): Int = input.lines()
.chunked(3)
.map { group ->
group.first().toList()
.intersect(group[1].toSet())
.intersect(group[2].toSet())
.first()
}.sumOf { convertToScore(it) }
private fun convertToScore(char: Char): Int =
if (char.isUpperCase()) char.code.minus(UPPERCASE_DIFFERENCE)
else char.code.minus(LOWERCASE_DIFFERENCE) | 0 | Kotlin | 0 | 0 | 355f476765948c79bfc61367c1afe446fe9f6083 | 880 | aoc2022Kotlin | Apache License 2.0 |
aoc-2015/src/main/kotlin/nl/jstege/adventofcode/aoc2015/days/Day21.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2015.days
import nl.jstege.adventofcode.aoccommon.days.Day
/**
*
* @author <NAME>
*/
class Day21 : Day(title = "RPG Simulator 20XX") {
private companion object Configuration {
private val ITEMS = listOf(
8 to Item.Weapon(4),
10 to Item.Weapon(5),
24 to Item.Weapon(6),
40 to Item.Weapon(7),
74 to Item.Weapon(8),
0 to Item.Armor(0),
13 to Item.Armor(1),
31 to Item.Armor(2),
53 to Item.Armor(3),
75 to Item.Armor(4),
102 to Item.Armor(5),
0 to Item.Ring(0, Item.ItemType.ATTACK),
0 to Item.Ring(0, Item.ItemType.ATTACK),
25 to Item.Ring(1, Item.ItemType.ATTACK),
50 to Item.Ring(2, Item.ItemType.ATTACK),
100 to Item.Ring(3, Item.ItemType.ATTACK),
20 to Item.Ring(1, Item.ItemType.DEFENSE),
40 to Item.Ring(2, Item.ItemType.DEFENSE),
80 to Item.Ring(3, Item.ItemType.DEFENSE)
)
private val WEAPONS = ITEMS.filter { it.second is Item.Weapon }
private val ARMOR = ITEMS.filter { it.second is Item.Armor }
private val RINGS = ITEMS.filter { it.second is Item.Ring }
private val OWN_PLAYER = listOf(
"Hit Points: 100",
"Damage: 0",
"Armor: 0"
)
}
override fun first(input: Sequence<String>) =
generateBuilds(Player.of(OWN_PLAYER))
.generateFights(Player.of(input.toList()))
.filter { it.second }.map { it.first }.min()!!
override fun second(input: Sequence<String>) =
generateBuilds(Player.of(OWN_PLAYER))
.generateFights(Player.of(input.toList()))
.filter { !it.second }.map { it.first }.max()!!
private fun generateBuilds(player: Player) =
WEAPONS.flatMap { weapon ->
ARMOR.flatMap { armor ->
RINGS.flatMap { ring1 ->
RINGS.filter { ring -> ring !== ring1 }
.map { ring2 -> listOf(weapon, armor, ring1, ring2) }
}
}
}
.asSequence()
.map { build ->
val p = player.copy()
p.weapon = build[0].second as Item.Weapon
p.armor = build[1].second as Item.Armor
p.rings[0] = build[2].second as Item.Ring
p.rings[1] = build[3].second as Item.Ring
build.sumBy { it.first } to p
}
private fun Sequence<Pair<Int, Player>>.generateFights(boss: Player) =
this.map { (cost, player) -> cost to player.fight(boss.copy()) }
private data class Player(var hitPoints: Int, var unarmedAttack: Int, var unarmedDefense: Int) {
var weapon = Item.Weapon(unarmedAttack)
var armor = Item.Armor(unarmedDefense)
val rings = mutableListOf(
Item.Ring(0, Item.ItemType.ATTACK),
Item.Ring(0, Item.ItemType.ATTACK)
)
val attack: Int
get() = weapon.rating + rings
.filter { it.itemType == Item.ItemType.ATTACK }
.sumBy { it.rating }
val defense: Int
get() = armor.rating + rings
.filter { it.itemType == Item.ItemType.DEFENSE }
.sumBy { it.rating }
fun fight(other: Player) =
this.hitPoints - (other.attack - this.defense) *
(Math.ceil(other.hitPoints / (this.attack - other.defense).toDouble())
.toInt() - 1) >= 0
companion object Parser {
@JvmStatic
fun of(input: List<String>): Player {
val hp = input[0].substring(12).toInt()
val atk = input[1].substring(8).toInt()
val def = input[2].substring(7).toInt()
return Player(hp, atk, def)
}
}
}
private sealed class Item(val rating: Int, val itemType: ItemType) {
class Weapon(rating: Int) : Item(rating, ItemType.ATTACK)
class Armor(rating: Int) : Item(rating, ItemType.DEFENSE)
class Ring(rating: Int, itemType: ItemType) : Item(rating, itemType)
enum class ItemType {
ATTACK, DEFENSE
}
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 4,331 | AdventOfCode | MIT License |
src/main/kotlin/_0064_MinimumPathSum.kt | ryandyoon | 664,493,186 | false | null | import kotlin.math.min
// https://leetcode.com/problems/minimum-path-sum
fun minPathSum(grid: Array<IntArray>): Int {
val lastRow = grid.lastIndex
val lastCol = grid.first().lastIndex
val memo = Array(lastRow + 1) { IntArray(lastCol + 1) }
memo[lastRow][lastCol] = grid[lastRow][lastCol]
for (row in lastRow - 1 downTo 0) {
memo[row][lastCol] = grid[row][lastCol] + memo[row + 1][lastCol]
}
for (col in lastCol - 1 downTo 0) {
memo[lastRow][col] = grid[lastRow][col] + memo[lastRow][col + 1]
}
for (row in lastRow - 1 downTo 0) {
for (col in lastCol - 1 downTo 0) {
memo[row][col] = grid[row][col] + min(memo[row + 1][col], memo[row][col + 1])
}
}
return memo[0][0]
}
| 0 | Kotlin | 0 | 0 | 7f75078ddeb22983b2521d8ac80f5973f58fd123 | 757 | leetcode-kotlin | MIT License |
aoc-2018/src/main/kotlin/nl/jstege/adventofcode/aoc2018/days/Day08.kt | JStege1206 | 92,714,900 | false | null | package nl.jstege.adventofcode.aoc2018.days
import nl.jstege.adventofcode.aoccommon.days.Day
import nl.jstege.adventofcode.aoccommon.utils.extensions.head
class Day08 : Day(title = "Memory Maneuver") {
override fun first(input: Sequence<String>): Any =
input.head
.parse()
.sumMetadata()
override fun second(input: Sequence<String>): Any =
input.head
.parse()
.calculateNodeValues()
.sum()
fun String.parse(): Iterator<Int> = object : Iterator<Int> {
val iterator = this@parse.trim().iterator()
override fun hasNext(): Boolean = iterator.hasNext()
override fun next(): Int {
var n = 0
var c = iterator.nextChar()
do {
n = n * 10 + (c - '0')
if (iterator.hasNext()) c = iterator.nextChar()
} while (c != ' ' && iterator.hasNext())
return n
}
}
private fun Iterator<Int>.sumMetadata(): Int =
(next() to next())
.let { (children, metadata) ->
(0 until children)
.sumBy { sumMetadata() } + (0 until metadata).sumBy { next() }
}
private fun Iterator<Int>.calculateNodeValues(): List<Int> =
(next() to next())
.let { (children, metadata) ->
if (children == 0)
(0 until metadata).map { next() }
else
(0 until children)
.map { calculateNodeValues() }
.slice((0 until metadata).map { next() - 1 }.filter { it < children })
.flatten()
}
}
| 0 | Kotlin | 0 | 0 | d48f7f98c4c5c59e2a2dfff42a68ac2a78b1e025 | 1,705 | AdventOfCode | MIT License |
06/06.kt | Steve2608 | 433,779,296 | false | {"Python": 34592, "Julia": 13999, "Kotlin": 11412, "Shell": 349, "Cython": 211} | import java.io.File
const val resetDays = 6
const val newbornDays = 8
private class Population(data: IntArray) : Iterable<MutableMap.MutableEntry<Int, Long>> {
constructor() : this(IntArray(0))
private val populationCount: MutableMap<Int, Long> = HashMap()
val nFish: Long
get() = populationCount.values.sum()
init {
data.forEach {
populationCount[it] = populationCount.getOrDefault(it, 0) + 1
}
}
fun addPopulation(age: Int, amount: Long) {
populationCount[age] = populationCount.getOrDefault(age, 0) + amount
}
override fun iterator(): MutableIterator<MutableMap.MutableEntry<Int, Long>> = populationCount.iterator()
}
private fun simulatePopulation(data: IntArray, days: Int): Long {
var pop = Population(data)
for (i in 1..days) {
val popNext = Population()
for ((key, value) in pop) {
if (key <= 0) {
popNext.addPopulation(newbornDays, value)
popNext.addPopulation(resetDays, value)
} else {
popNext.addPopulation(key - 1, value)
}
}
pop = popNext
}
return pop.nFish
}
private fun part1(data: IntArray) = simulatePopulation(data, days = 80)
private fun part2(data: IntArray) = simulatePopulation(data, days = 256)
fun main() {
fun File.readData() = this.readLines()[0].split(",").map { it.toInt() }.toIntArray()
val example = File("example.txt").readData()
assert(5934L == part1(example)) { "Expected 5934 fish" }
assert(26984457539L == part2(example)) { "Expected 26984457539 fish" }
val data = File("input.txt").readData()
println(part1(data))
println(part2(data))
} | 0 | Python | 0 | 1 | 2dcad5ecdce5e166eb053593d40b40d3e8e3f9b6 | 1,545 | AoC-2021 | MIT License |
src/commonMain/kotlin/advent2020/day09/Day09Puzzle.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day09
import advent2020.ProgressLogger
internal fun String.parsedData() = trim().lines().map(String::toLong)
fun valid(preamble: List<Long>, expectedSum: Long): Boolean {
val sortedPreamble = preamble.sorted()
var startIndex = 0
var endIndex = sortedPreamble.lastIndex
while (startIndex < endIndex) {
val sum = sortedPreamble[startIndex] + sortedPreamble[endIndex]
when {
sum < expectedSum -> startIndex++
sum > expectedSum -> endIndex--
else -> return true
}
}
return false
}
fun firstInvalid(data: List<Long>, preambleLength: Int = 25) = (preambleLength..data.lastIndex)
.first { index ->
val preamble = data.subList(index - preambleLength, index)
(!valid(preamble, data[index]))
}
.let { data[it] }
fun List<Long>.minPlusMax(): Long {
var minimum = this[0]
var maximum = this[0]
forEach {
if (it < minimum) minimum = it
if (it > maximum) maximum = it
}
return minimum + maximum
}
interface Day09ProgressLogger : ProgressLogger {
suspend fun startingSearch(data: List<Long>, start: Int, end: Int, sum: Long, expectedSum: Long) {}
suspend fun expanding(start: Int, end: Int, sum: Long) {}
suspend fun narrowing(start: Int, end: Int, sum: Long) {}
suspend fun shifting(start: Int, end: Int, sum: Long) {}
suspend fun finished(start: Int, end: Int, sum: Long) {}
}
suspend fun contiguousMinPlusMax(
data: List<Long>,
expectedSum: Long,
logger: ProgressLogger = object : Day09ProgressLogger {},
) = contiguous(data, expectedSum, logger = logger)
.let { (start, end) -> data.subList(start, end) }
.minPlusMax()
suspend fun contiguous(
data: List<Long>,
expectedSum: Long,
minSize: Int = 2,
logger: ProgressLogger = object : Day09ProgressLogger {},
): Pair<Int, Int> {
logger as Day09ProgressLogger
var start = 0
var end = start + minSize
var sum = data.subList(start, end).sum()
logger.startingSearch(data, start, end, sum, expectedSum)
while (start < data.size - minSize) when {
sum < expectedSum -> sum = (sum + data[end++]).also { logger.expanding(start, end, sum) }
sum > expectedSum -> sum = (sum - data[start++]).also { logger.narrowing(start, end, sum) }
end - start < minSize -> sum = (sum - data[start++] + data[end++]).also { logger.shifting(start, end, sum) }
else -> return (start to end).also { logger.finished(start, end, sum)}
}
error("answer not found")
}
fun part1(input: String) = firstInvalid(input.parsedData()).toString()
suspend fun part2(input: String, logger: ProgressLogger = object : Day09ProgressLogger {}) =
contiguousMinPlusMax(input.parsedData(), firstInvalid(input.parsedData()), logger).toString()
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 2,836 | advent-of-code-2020 | MIT License |
UncommonWordsFromTwoSentences.kt | ncschroeder | 604,822,497 | false | {"Kotlin": 19399} | /*
https://leetcode.com/problems/uncommon-words-from-two-sentences/
A sentence is a string of single-space separated words where each word consists only of lowercase letters.
A word is uncommon if it appears exactly once in one of the sentences, and does not appear in the other sentence.
Given two sentences `s1` and `s2`, return a list of all the uncommon words. You may return the answer in any order.
Constraints:
- 1 <= s1.length, s2.length <= 200
- s1 and s2 consist of lowercase English letters and spaces
- s1 and s2 do not have leading or trailing spaces
- All the words in s1 and s2 are separated by a single space
*/
fun uncommonFromSentences(s1: String, s2: String): Array<String> {
fun getWordsStuff(sentence: String): Pair<Set<String>, Sequence<String>> {
val allWords = mutableSetOf<String>()
val wordsThatAppearOnce = mutableSetOf<String>()
for (word: String in sentence.splitToSequence(" ")) {
if (word !in allWords) {
allWords.add(word)
wordsThatAppearOnce.add(word)
} else if (word in wordsThatAppearOnce) {
wordsThatAppearOnce.remove(word)
}
}
return Pair(allWords, wordsThatAppearOnce.asSequence())
}
val ( allWords1, wordsThatAppearOnce1 ) = getWordsStuff(s1)
val ( allWords2, wordsThatAppearOnce2 ) = getWordsStuff(s2)
return wordsThatAppearOnce1.minus(allWords2)
.plus(wordsThatAppearOnce2.minus(allWords1))
.toList()
.toTypedArray()
} | 0 | Kotlin | 0 | 0 | c77d0c8bb0595e61960193fc9b0c7a31952e8e48 | 1,544 | Coding-Challenges | MIT License |
src/test/kotlin/Day17.kt | christof-vollrath | 317,635,262 | false | null | import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeIn
import io.kotest.matchers.collections.shouldNotBeIn
import io.kotest.matchers.shouldBe
/*
--- Day 17: Conway Cubes ---
See https://adventofcode.com/2020/day/17
*/
fun Map<Coord3, Char>.cycle(): Map<Coord3, Char> {
val survivers = keys.mapNotNull { coord3 ->
val neighborCount = coord3.neighbors26().count { get(it) == '#' }
if (neighborCount in 2..3) coord3 to '#'
else null
}
val newborns = keys.flatMap { coord3 ->
coord3.neighbors26().mapNotNull { neighbor -> // check neighbors for new born
val neighborCountOfNeighbor = neighbor.neighbors26().count { get(it) == '#' }
if (neighborCountOfNeighbor == 3) neighbor to '#'
else null
}
}
return (survivers + newborns).toMap()
}
fun Map<Coord3, Char>.toPrintableString(): String {
val maxX = keys.map { it.x }.maxOrNull()!!
val minX = keys.map { it.x }.minOrNull()!!
val maxY = keys.map { it.y }.maxOrNull()!!
val minY = keys.map { it.y }.minOrNull()!!
val maxZ = keys.map { it.z }.maxOrNull()!!
val minZ = keys.map { it.z }.minOrNull()!!
return this.toPrintableString(minX..maxX, minY..maxY, minZ..maxZ)
}
fun Map<Coord3, Char>.toPrintableString(xRange: IntRange, yRange: IntRange, zRange: IntRange) =
zRange.map { z->
"z=$z\n" +
yRange.map { y ->
xRange.map { x ->
getOrDefault(Coord3(x, y, z), '.')
}.joinToString("")
}.joinToString("\n")
}.joinToString("\n\n")
fun parseCubeLayer(input: String): Map<Coord3, Char> {
val inputLines = input.split("\n")
val sizeY = inputLines.size
val offsetY = sizeY / 2
val sizeX = inputLines[0].length
val offsetX = sizeX / 2
return inputLines.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') Coord3(x - offsetX, y - offsetY, 0) to c
else null
}
}.toMap()
}
fun Map<Coord4, Char>.cycle4(): Map<Coord4, Char> {
val survivers = keys.mapNotNull { coord4 ->
val neighborCount = coord4.neighbors80().count { get(it) == '#' }
if (neighborCount in 2..3) coord4 to '#'
else null
}
val newborns = keys.flatMap { coord4 ->
coord4.neighbors80().mapNotNull { neighbor -> // check neighbors for new born
val neighborCountOfNeighbor = neighbor.neighbors80().count { get(it) == '#' }
if (neighborCountOfNeighbor == 3) neighbor to '#'
else null
}
}
return (survivers + newborns).toMap()
}
fun Map<Coord4, Char>.toPrintableString4(): String {
val maxX = keys.map { it.x }.maxOrNull()!!
val minX = keys.map { it.x }.minOrNull()!!
val maxY = keys.map { it.y }.maxOrNull()!!
val minY = keys.map { it.y }.minOrNull()!!
val maxZ = keys.map { it.z }.maxOrNull()!!
val minZ = keys.map { it.z }.minOrNull()!!
val maxW = keys.map { it.w }.maxOrNull()!!
val minW = keys.map { it.w }.minOrNull()!!
return this.toPrintableString4(minX..maxX, minY..maxY, minZ..maxZ, minW..maxW)
}
fun Map<Coord4, Char>.toPrintableString4(xRange: IntRange, yRange: IntRange, zRange: IntRange, wRange: IntRange) =
wRange.map { w ->
zRange.map { z ->
"z=$z, w=$w\n" +
yRange.map { y ->
xRange.map { x ->
getOrDefault(Coord4(x, y, z, w), '.')
}.joinToString("")
}.joinToString("\n")
}.joinToString("\n\n")
}.joinToString("\n\n")
fun parseCubeLayer4(input: String): Map<Coord4, Char> {
val inputLines = input.split("\n")
val sizeY = inputLines.size
val offsetY = sizeY / 2
val sizeX = inputLines[0].length
val offsetX = sizeX / 2
return inputLines.flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, c ->
if (c == '#') Coord4(x - offsetX, y - offsetY, 0, 0) to c
else null
}
}.toMap()
}
class Day17_Part1 : FunSpec({
context("neighbors 3d") {
context("find neighbors for 0, 0, 0") {
val neighbors = Coord3(0, 0, 0).neighbors26()
test("should have found neighbors") {
neighbors.size shouldBe 26
Coord3(0, 0, 0) shouldNotBeIn neighbors
Coord3(1, 0, 0) shouldBeIn neighbors
}
}
context("find neighbors for 1, 2, 3") {
val neighbors = Coord3(1, 2, 3).neighbors26()
test("should have found neighbors") {
neighbors.size shouldBe 26
Coord3(2, 2, 2) shouldBeIn neighbors
Coord3(0, 2, 3) shouldBeIn neighbors
}
}
}
context("parse cube layer") {
val input = """
.#.
..#
###
""".trimIndent()
val cube = parseCubeLayer(input)
test("cube should have the right active points") {
cube[Coord3(1, 1, 0)] shouldBe '#'
cube[Coord3(0, -1, 0)] shouldBe '#'
cube[Coord3(0, 0, 0)] shouldBe null
}
}
context("print cube ") {
val input = """
.#.
..#
###
""".trimIndent()
val cube = parseCubeLayer(input)
test("cube should be printed correctly") {
cube.toPrintableString(-1..1, -1..1, 0..0) shouldBe """
z=0
.#.
..#
###
""".trimIndent()
}
}
context("apply cycles") {
var cube = parseCubeLayer("""
.#.
..#
###
""".trimIndent())
context("apply one cycle") {
cube = cube.cycle()
cube.toPrintableString() shouldBe """
z=-1
#..
..#
.#.
z=0
#.#
.##
.#.
z=1
#..
..#
.#.
""".trimIndent()
}
context("apply second cycle") {
cube = cube.cycle()
cube.toPrintableString() shouldBe """
z=-2
.....
.....
..#..
.....
.....
z=-1
..#..
.#..#
....#
.#...
.....
z=0
##...
##...
#....
....#
.###.
z=1
..#..
.#..#
....#
.#...
.....
z=2
.....
.....
..#..
.....
.....
""".trimIndent()
}
context("apply third cycle") {
cube = cube.cycle()
cube.toPrintableString() shouldBe """
z=-2
.......
.......
..##...
..###..
.......
.......
.......
z=-1
..#....
...#...
#......
.....##
.#...#.
..#.#..
...#...
z=0
...#...
.......
#......
.......
.....##
.##.#..
...#...
z=1
..#....
...#...
#......
.....##
.#...#.
..#.#..
...#...
z=2
.......
.......
..##...
..###..
.......
.......
.......
""".trimIndent()
}
context("apply three more cycle") {
repeat(3) {
cube = cube.cycle()
}
test("should have right number of active cubes") {
cube.size shouldBe 112
}
}
}
})
class Day17_Part1_Exercise: FunSpec({
val input = readResource("day17Input.txt")!!
var cube = parseCubeLayer(input)
repeat(6) {
cube = cube.cycle()
}
test("should have right number of active cubes") {
cube.size shouldBe 338
}
})
class Day17_Part2 : FunSpec({
context("neighbors 4d") {
context("find neighbors for 0, 0, 0, 0") {
val neighbors = Coord4(0, 0, 0, 0).neighbors80()
test("should have found neighbors") {
neighbors.size shouldBe 80
Coord4(0, 0, 0, 0) shouldNotBeIn neighbors
Coord4(1, 0, 0, 1) shouldBeIn neighbors
}
}
context("find neighbors for 1, 2, 3, 4") {
val neighbors = Coord4(1, 2, 3, 4).neighbors80()
test("should have found neighbors") {
neighbors.size shouldBe 80
Coord4(2, 2, 2, 3) shouldBeIn neighbors
Coord4(0, 2, 3, 5) shouldBeIn neighbors
}
}
}
context("parse cube layer 4d") {
val input = """
.#.
..#
###
""".trimIndent()
val cube = parseCubeLayer4(input)
test("cube should have the right active points") {
cube[Coord4(1, 1, 0, 0)] shouldBe '#'
cube[Coord4(0, -1, 0, 0)] shouldBe '#'
cube[Coord4(0, 0, 0, 0)] shouldBe null
}
}
context("print cube 4d") {
val input = """
.#.
..#
###
""".trimIndent()
val cube = parseCubeLayer4(input)
test("cube should be printed correctly") {
cube.toPrintableString4(-1..1, -1..1, 0..0, 0..0) shouldBe """
z=0, w=0
.#.
..#
###
""".trimIndent()
}
}
context("apply cycles 4d") {
var cube = parseCubeLayer4("""
.#.
..#
###
""".trimIndent())
context("apply one cycle") {
cube = cube.cycle4()
cube.toPrintableString4() shouldBe """
z=-1, w=-1
#..
..#
.#.
z=0, w=-1
#..
..#
.#.
z=1, w=-1
#..
..#
.#.
z=-1, w=0
#..
..#
.#.
z=0, w=0
#.#
.##
.#.
z=1, w=0
#..
..#
.#.
z=-1, w=1
#..
..#
.#.
z=0, w=1
#..
..#
.#.
z=1, w=1
#..
..#
.#.
""".trimIndent()
}
context("apply five more cycle") {
repeat(5) {
cube = cube.cycle4()
}
test("should have right number of active cubes") {
cube.size shouldBe 848
}
}
}
})
class Day17_Part2_Exercise: FunSpec({
val input = readResource("day17Input.txt")!!
var cube = parseCubeLayer4(input)
repeat(6) {
cube = cube.cycle4()
}
test("should have right number of active cubes") {
cube.size shouldBe 2440
}
})
| 1 | Kotlin | 0 | 0 | 8ad08350aa4bd1a29b7e18765fc7a2d6de8021e8 | 11,422 | advent_of_code_2020 | Apache License 2.0 |
src/algorithmdesignmanualbook/sorting/MergeSort.kt | realpacific | 234,499,820 | false | null | package algorithmdesignmanualbook.sorting
import utils.assertArraysSame
import java.util.*
private fun mergeSort(array: IntArray, low: Int, high: Int) {
if (array.isEmpty()) {
return
}
// WARNING: if statement and not while
if (low < high) {
val mid = (low + high) / 2
// break left
mergeSort(array, low, mid)
// break right
mergeSort(array, mid + 1, high)
// sort and merge
kSortedListMerge(array, low, high, mid)
}
}
fun kSortedListMerge(array: IntArray, low: Int, high: Int, mid: Int) {
val queue1 = LinkedList<Int>()
val queue2 = LinkedList<Int>()
for (i in low..mid) {
queue1.add(array[i])
}
for (i in mid + 1..high) {
queue2.add(array[i])
}
var i = low
// do till one of them is empty
while (queue1.isNotEmpty() && queue2.isNotEmpty()) {
// pick the smallest of item; which is at head since at last level, only 1 item remains
if (queue1.peek() < queue2.peek()) {
array[i] = queue1.pop()
} else {
array[i] = queue2.pop()
}
i++
}
// Remaining items in queue1
while (queue1.isNotEmpty()) {
array[i] = queue1.pop()
i++
}
// Remaining items in queue2
while (queue2.isNotEmpty()) {
array[i] = queue2.pop()
i++
}
}
fun main() {
val input1 = intArrayOf(6, 8, 1, 5, 2, 9, 11)
mergeSort(input1, 0, input1.lastIndex)
println(Arrays.toString(input1))
assertArraysSame(expected = arrayOf(1, 2, 5, 6, 8, 9, 11), actual = input1.toTypedArray())
val input2 = intArrayOf(8, 1, 5, 2, 9, 11)
mergeSort(input2, 0, input2.lastIndex)
println(Arrays.toString(input2))
assertArraysSame(expected = arrayOf(1, 2, 5, 8, 9, 11), actual = input2.toTypedArray())
} | 4 | Kotlin | 5 | 93 | 22eef528ef1bea9b9831178b64ff2f5b1f61a51f | 1,841 | algorithms | MIT License |
src/lib/lib.kt | somei-san | 476,528,544 | false | {"Kotlin": 12475} | package lib
import java.util.*
// 約数のList
fun divisor(value: Long): List<Long> {
val max = Math.sqrt(value.toDouble()).toLong()
return (1..max)
.filter { value % it == 0L }
.map { listOf(it, value / it) }
.flatten()
.sorted()
}
// 範囲内の素数を取得
// fromだけ指定すると戻り値の個数で素数判定ができる
fun prime(from: Long, to: Long = from): List<Long> {
return (from..to).filter { i ->
val max = Math.sqrt(i.toDouble()).toLong()
(2..max).all { j -> i % j != 0L }
}
}
// 渡された値が素数か判定
fun isPrime(source: Int): Boolean {
return prime(source.toLong()).any()
}
// 素因数分解
fun decom(value: Long): List<Long> {
if (value == 1L) return listOf(1)
val max = Math.sqrt(value.toDouble()).toLong()
return prime(2, max).filter { value % it == 0L }
}
// 最大公約数
fun gcd(a: Long, b: Long): Long {
return if (a % b == 0L) b else gcd(b, a % b)
}
// 文字列を入れ替え
fun swap(base: String, a: String, b: String): String {
return base.map {
when (it) {
a.toCharArray()[0] -> b
b.toCharArray()[0] -> a
else -> it.toString()
}
}.joinToString()
}
/**
* リストをスタックに変換する
* @param list リスト
* @return スタック
*/
fun listToStack(list: List<Int>): Stack<Int> {
// スタック
val stack = Stack<Int>()
for (e in list) {
stack.push(e)
}
return stack
}
/**
* ユークリッドの互除法を用いて、最大公約数を導出する
* @param list 最大公約数を求める対象となる数が格納されたリスト
* @return 最大公約数
*/
fun gcd(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// ユークリッドの互除法を用いて、最大公約数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最大公約数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数のうち、小さい方の数のインデックス
val minIndex = if (pops[1] < pops[0]) {
1
} else {
0
}
// スタックからpopした2つの数のうち、小さい方の数をpush
stack.push(pops[minIndex])
// スタックからpopした2つの数の剰余
val r = pops[(minIndex + 1) % 2] % pops[minIndex]
// スタックからpopした2つの数に剰余があるならば、それをpush
if (0 < r) {
stack.push(r)
}
}
// 最大公約数を返す
return stack.pop()
}
/**
* 最小公倍数を導出する
* @param list 最小公倍数を求める対象となる数が格納されたリスト
* @return 最小公倍数
*/
fun lcm(list: List<Int>): Int {
// 最大公約数を求める対象となる数が格納されたスタック
val stack = listToStack(list)
// 最小公倍数を導出する
// (最終的にスタック内に1つだけ数が残り、それが最小公倍数となる)
while (1 < stack.size) {
// スタックから2つの数をpop
val pops = (0 until 2).map {
stack.pop()
}
// スタックからpopした2つの数の最小公倍数をpush
stack.push(pops[0] * pops[1] / gcd(pops))
}
// 最小公倍数を返す
return stack.pop()
}
| 0 | Kotlin | 0 | 0 | 43ea45fc0bc135d6d33af1fd0d7de6a7b3b651ec | 3,643 | atcoder-kotline | MIT License |
kotlin/src/main/kotlin/dev/mikeburgess/euler/problems/Problem038.kt | mddburgess | 261,028,925 | false | null | package dev.mikeburgess.euler.problems
import dev.mikeburgess.euler.common.isPandigital
/**
* Take the number 192 and multiply it by each of 1, 2, and 3:
*
* 192 × 1 = 192
* 192 × 2 = 384
* 192 × 3 = 576
*
* By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576
* the concatenated product of 192 and (1,2,3)
*
* The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the
* pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5).
*
* What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated
* product of an integer with (1,2, ... , n) where n > 1?
*/
class Problem038 : Problem {
override fun solve(): Long =
(9487 downTo 9234)
.map { it * 100002L }
.first { it.isPandigital() }
}
| 0 | Kotlin | 0 | 0 | 86518be1ac8bde25afcaf82ba5984b81589b7bc9 | 869 | project-euler | MIT License |
src/Day14.kt | SnyderConsulting | 573,040,913 | false | {"Kotlin": 46459} | fun main() {
fun part1(input: List<String>): Int {
val rockLines = input.map { line ->
line.split(" -> ").map {
Coordinate.from(it)
}.fillRockLines()
}.flatten()
val (left, right, bottom) = rockLines.getEdgeLocations()
val grid = List(bottom + 1) { MutableList(right - left + 1) { false } }
rockLines.forEach { rock ->
grid[rock.y][rock.x - left] = true
}
grid.forEach { line ->
println(line.map { isFilled ->
if (isFilled) "#" else "."
})
}
var counter = 0
var sandStopped = true
while (sandStopped) {
sandStopped = simulateSandP1(grid, 500 - left, bottom, right - left)
if (sandStopped) {
counter++
}
}
return counter
}
fun part2(input: List<String>): Int {
val rockLines = input.map { line ->
line.split(" -> ").map {
Coordinate.from(it)
}.fillRockLines()
}.flatten().toMutableList()
val (_, _, bottom) = rockLines.getEdgeLocations()
var counter = 0
var sandStopped = true
while (sandStopped) {
counter++
sandStopped = simulateSandP2(filledLocations = rockLines, bottom + 2)
println(rockLines.size)
}
return counter
}
val input = readInput("Day14")
println(part1(input))
println(part2(input))
}
fun simulateSandP1(grid: List<MutableList<Boolean>>, startingX: Int, rockBottom: Int, rockRight: Int): Boolean {
val sandPosition = Coordinate(startingX, 0)
while (true) {
if (sandPosition.y == rockBottom) {
return false
}
if (!grid[sandPosition.y + 1][sandPosition.x]) {
//can move down
sandPosition.y += 1
} else if (sandPosition.x == 0) {
return false
} else if (!grid[sandPosition.y + 1][sandPosition.x - 1]) {
//can move left
sandPosition.y += 1
sandPosition.x -= 1
} else if (sandPosition.x == rockRight) {
return false
} else if (!grid[sandPosition.y + 1][sandPosition.x + 1]) {
//can move right
sandPosition.y += 1
sandPosition.x += 1
} else {
grid[sandPosition.y][sandPosition.x] = true
return true
}
}
}
fun simulateSandP2(filledLocations: MutableList<Coordinate>, rockBottom: Int): Boolean {
val sandPosition = Coordinate(500, 0)
while (true) {
if (sandPosition.y + 1 == rockBottom) {
filledLocations.add(sandPosition)
return true
} else if (!filledLocations.contains(Coordinate(sandPosition.x, sandPosition.y + 1))) {
//can move down
sandPosition.y += 1
} else if (!filledLocations.contains(Coordinate(sandPosition.x - 1, sandPosition.y + 1))) {
//can move left
sandPosition.y += 1
sandPosition.x -= 1
} else if (!filledLocations.contains(Coordinate(sandPosition.x + 1, sandPosition.y + 1))) {
//can move right
sandPosition.y += 1
sandPosition.x += 1
} else {
return if (sandPosition.x == 500 && sandPosition.y == 0) {
false
} else {
filledLocations.add(sandPosition)
true
}
}
}
}
data class Coordinate(var x: Int, var y: Int) {
companion object {
fun from(string: String): Coordinate {
return Coordinate(
x = string.split(",")[0].toInt(),
y = string.split(",")[1].toInt(),
)
}
}
}
fun List<Coordinate>.fillRockLines(): List<Coordinate> {
val rockLines = mutableListOf<Coordinate>()
windowed(2).forEach { (start, end) ->
rockLines.add(start)
rockLines.add(end)
if (start.x == end.x) {
//moving vertically
if (start.y > end.y) {
//moving up
repeat(start.y - end.y) {
rockLines.add(
Coordinate(start.x, start.y - it)
)
}
} else {
//moving down
repeat(end.y - start.y) {
rockLines.add(
Coordinate(start.x, start.y + it)
)
}
}
} else if (start.y == end.y) {
//moving horizontally
if (start.x > end.x) {
//moving left
repeat(start.x - end.x) {
rockLines.add(
Coordinate(start.x - it, start.y)
)
}
} else {
//moving right
repeat(end.x - start.x) {
rockLines.add(
Coordinate(start.x + it, start.y)
)
}
}
}
}
return rockLines.distinct()
}
//Left, Right, Bottom
fun List<Coordinate>.getEdgeLocations(): List<Int> {
val left = minBy { it.x }.x
val right = maxBy { it.x }.x
val bottom = maxBy { it.y }.y
return listOf(left, right, bottom)
} | 0 | Kotlin | 0 | 0 | ee8806b1b4916fe0b3d576b37269c7e76712a921 | 5,383 | Advent-Of-Code-2022 | Apache License 2.0 |
src/Day17.kt | dakr0013 | 572,861,855 | false | {"Kotlin": 105418} | import kotlin.test.assertEquals
fun main() {
fun part1(input: List<String>): Long {
val chamber = CaveChamber(JetPattern(input.first()))
repeat(2022) { chamber.dropRock() }
return chamber.towerSize
}
fun part2(input: List<String>): Long {
val chamber = CaveChamber(JetPattern(input.first()))
val (initialPart, repeatingPart) = chamber.findRepeatingPattern()
var remainingRocks = 1_000_000_000_000
var towerSize = 0L
towerSize += initialPart.towerSize
remainingRocks -= initialPart.rockCount
val possibleRepeats = remainingRocks / repeatingPart.rockCount
towerSize += possibleRepeats * repeatingPart.towerSize
remainingRocks %= repeatingPart.rockCount
val tempTowerSize = chamber.towerSize
for (i in 1..remainingRocks) {
chamber.dropRock()
}
val lastPartTowerSize = chamber.towerSize - tempTowerSize
return towerSize + lastPartTowerSize
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day17_test")
assertEquals(3068, part1(testInput))
assertEquals(1_514_285_714_288, part2(testInput))
val input = readInput("Day17")
println(part1(input))
println(part2(input))
}
data class TowerPart(val towerSize: Long, val rockCount: Long)
data class RepeatingResult(val initialPart: TowerPart, val repeatingPart: TowerPart)
class CaveChamber(private val jetPattern: JetPattern) {
private val rockSpawner = RockSpawner()
private val walls = 0b1_0000000_1
private val floor = 0b1_1111111_1
private val largestRockSize = 4
private val airBufferBetweenTowerTopAndNewRock = 3
private val airBufferSize = largestRockSize + airBufferBetweenTowerTopAndNewRock
private val chamber: MutableList<Int> =
buildList {
repeat(airBufferSize) { add(walls) }
add(floor)
}
.toMutableList()
var towerSize = 0L
private set
fun dropRock() {
var rock = rockSpawner.next()
var indexOfUpperRockEdge = largestRockSize - rock.size
while (true) {
// push by jet of hot gas
val nextRock = rock.push(jetPattern.next())
var isNextRockValid = true
for (i in rock.lastIndex downTo 0) {
val rockLineIntersects = (nextRock[i] and chamber[i + indexOfUpperRockEdge]) != 0
if (rockLineIntersects) {
isNextRockValid = false
break
}
}
if (isNextRockValid) rock = nextRock
// fall down
var isMoveDownValid = true
for (i in rock.lastIndex downTo 0) {
val rockLineIntersects = (rock[i] and chamber[i + indexOfUpperRockEdge + 1]) != 0
if (rockLineIntersects) {
isMoveDownValid = false
break
}
}
if (isMoveDownValid) indexOfUpperRockEdge++ else break
}
// add stopped rock to chamber
for (i in rock.indices) {
chamber[indexOfUpperRockEdge + i] = chamber[indexOfUpperRockEdge + i] or rock[i]
}
// calculate added height by this rock
val addedHeight = airBufferSize - indexOfUpperRockEdge
if (addedHeight > 0) {
towerSize += addedHeight
repeat(addedHeight) { chamber.add(0, walls) }
}
// just some random values to keep list size small
// this way chamber only has around top 100 lines
// it is unlikely that a rock will fall down more than 100
if (chamber.size > 100) repeat(5) { chamber.removeLast() }
}
fun findRepeatingPattern(): RepeatingResult {
data class JetPatternTripResult(
val rockCountDeltaSinceLastTrip: Long,
val towerSizeDeltaSinceLastTrip: Long,
val nextJetPatternIndex: Int,
val nextRockType: Int,
) {
override fun toString(): String =
"JetPatternTripResult($rockCountDeltaSinceLastTrip, $towerSizeDeltaSinceLastTrip, $nextJetPatternIndex, $nextRockType)"
}
val tripResults: MutableList<JetPatternTripResult> = mutableListOf()
var jetPatternRoundTripCount = 0
var towerSizeLastTrip = 0L
var rockCountLastTrip = 0L
var rockCount = 0L
while (true) {
dropRock().also { rockCount++ }
if (jetPattern.roundTripCount > jetPatternRoundTripCount) {
jetPatternRoundTripCount++
val tripResult =
JetPatternTripResult(
rockCountDeltaSinceLastTrip = rockCount - rockCountLastTrip,
towerSizeDeltaSinceLastTrip = towerSize - towerSizeLastTrip,
nextJetPatternIndex = jetPattern.nextIndex,
nextRockType = rockSpawner.nextRockType,
)
tripResults.add(tripResult)
val sameResultIndex = tripResults.dropLast(1).indexOf(tripResult)
if (sameResultIndex >= 0) {
val patternSize = tripResults.lastIndex - sameResultIndex
if (tripResults.size >= patternSize * 2) {
val pattern1 = tripResults.slice(sameResultIndex + 1 - patternSize..sameResultIndex)
val pattern2 = tripResults.slice(sameResultIndex + 1..tripResults.lastIndex)
if (pattern1 == pattern2) {
val initialPattern = tripResults.slice(0..sameResultIndex - patternSize)
return RepeatingResult(
initialPart =
TowerPart(
initialPattern.sumOf { it.towerSizeDeltaSinceLastTrip },
initialPattern.sumOf { it.rockCountDeltaSinceLastTrip }),
repeatingPart =
TowerPart(
pattern1.sumOf { it.towerSizeDeltaSinceLastTrip },
pattern1.sumOf { it.rockCountDeltaSinceLastTrip }),
)
}
}
}
rockCountLastTrip = rockCount
towerSizeLastTrip = towerSize
}
}
}
override fun toString(): String {
return "Chamber: \n" + chamber.joinToString("\n") { it.toString(2).replace("0", " ") }
}
}
data class JetPattern(private val pattern: String) {
var roundTripCount = 0
private set
var nextIndex = 0
private set
/** @return true if next direction is left, else false */
fun next(): Boolean =
(pattern[nextIndex] == '<').also {
nextIndex = (nextIndex + 1) % pattern.length
if (nextIndex == 0) roundTripCount++
}
}
class RockSpawner {
var nextRockType = 0
private set
fun next(): IntArray =
when (nextRockType) {
0 ->
intArrayOf(
0b0_0011110_0,
)
1 ->
intArrayOf(
0b0_0001000_0,
0b0_0011100_0,
0b0_0001000_0,
)
2 ->
intArrayOf(
0b0_0000100_0,
0b0_0000100_0,
0b0_0011100_0,
)
3 ->
intArrayOf(
0b0_0010000_0,
0b0_0010000_0,
0b0_0010000_0,
0b0_0010000_0,
)
else ->
intArrayOf(
0b0_0011000_0,
0b0_0011000_0,
)
}.also { nextRockType = (nextRockType + 1) % 5 }
}
fun IntArray.push(shiftLeft: Boolean): IntArray = if (shiftLeft) this.shl() else this.shr()
fun IntArray.shl(): IntArray = IntArray(size) { i -> this[i].shl(1) }
fun IntArray.shr(): IntArray = IntArray(size) { i -> this[i].ushr(1) }
| 0 | Kotlin | 0 | 0 | 6b3adb09f10f10baae36284ac19c29896d9993d9 | 7,332 | aoc2022 | Apache License 2.0 |
shared/account/src/commonMain/kotlin/io/edugma/features/account/domain/usecase/MenuDataConverterUseCase.kt | Edugma | 474,423,768 | false | {"Kotlin": 971204, "Swift": 1255, "JavaScript": 1169, "HTML": 299, "Ruby": 102} | package io.edugma.features.account.domain.usecase
import io.edugma.features.account.domain.model.Personal
import io.edugma.features.account.domain.model.payments.Contract
import io.edugma.features.account.domain.model.performance.GradePosition
import kotlin.math.roundToInt
class MenuDataConverterUseCase {
fun convert(personal: Personal): PersonalData {
return personal.toPersonalData()
}
fun convert(contracts: List<Contract>): CurrentPayments? {
return contracts.getCurrent()
}
fun convert(performance: List<GradePosition>): CurrentPerformance? {
return performance.getCurrent()
}
private fun Personal.toPersonalData(): PersonalData {
return PersonalData(
description = description,
avatar = avatar,
name = name,
)
}
private fun List<Contract>.getCurrent(): CurrentPayments? {
return firstOrNull()?.let {
val sum = it.balance.toIntOrNull() ?: return null
val current = sum - (it.balance.toIntOrNull() ?: return null)
val debt = (it.balance.toIntOrNull() ?: return null) > 0
CurrentPayments(
type = it.title,
sum = sum,
current = current,
debt = debt,
)
}
}
private fun List<GradePosition>.getCurrent(): CurrentPerformance? {
fun getSortedMarks(marks: List<GradePosition>): Map<String, Int> {
val marksList = marks.map { it.grade?.value?.toString().orEmpty() }.let { list ->
mutableMapOf<String, Int>().apply {
list.toSet().forEach { put(it, list.count { mark -> mark == it }) }
keys.forEach { this[it] = ((this[it] ?: 0).toDouble() / list.size * 100).roundToInt() }
}
.filterNot { it.value == 0 }
}
val resultMap = mutableMapOf<String, Int>()
marksList.values.sorted().reversed().take(3).forEach {
marksList.forEach { (mark, percent) -> if (it == percent) resultMap[mark] = percent }
}
while (resultMap.keys.size > 3) {
resultMap.remove(resultMap.keys.last())
}
return resultMap
}
if (isEmpty()) return null
return CurrentPerformance(
0,
emptyMap(),
getSortedMarks(this),
)
}
}
data class PersonalData(
val description: String,
val avatar: String?,
val name: String,
)
data class CurrentPerformance(
val lastSemesterNumber: Int,
val lastSemester: Map<String, Int>,
val allSemesters: Map<String, Int>,
)
data class CurrentPayments(
val type: String,
val sum: Int,
val current: Int,
val debt: Boolean,
)
| 1 | Kotlin | 0 | 2 | 80e49696cbd50a47ad515481511d972c283acb3e | 2,816 | app | MIT License |
src/main/kotlin/me/peckb/aoc/_2015/calendar/day20/Day20.kt | peckb1 | 433,943,215 | false | {"Kotlin": 956135} | package me.peckb.aoc._2015.calendar.day20
import arrow.core.fold
import javax.inject.Inject
import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory
import kotlin.math.pow
import kotlin.math.sqrt
class Day20 @Inject constructor(private val generatorFactory: InputGeneratorFactory) {
fun partOne(filename: String) = generatorFactory.forFile(filename).readOne { input ->
val tooFar = input.toInt() / 10
(2 until tooFar step 2).first { sumOfFactors(it) >= tooFar }
}
fun partTwo(filename: String) = generatorFactory.forFile(filename).readOne { input ->
val cap = input.toInt()
// chosen "randomly" to limit our bounds
val array = Array(1_000_000) { 0 }
(1..cap).first { elf ->
(elf..(elf*50) step elf).forEach { house ->
if (house < array.size) {
array[house] += elf * 11
}
}
array[elf] >= cap
}
}
private fun sumOfFactors(num: Int): Int {
return primeFactors(num).groupBy { it }.fold(1.0) { acc, next ->
acc * ((next.key.toDouble().pow(next.value.size.toDouble() + 1.0) - 1) / (next.key - 1))
}.toInt()
}
@Suppress("unused")
/**
* Leaving in for historical learnings. Originally I just went piece meal finding the actual
* factors, and summing them up. And then after getting the stars, found some "more memory,
* less time" solutions
*/
private fun factorsOfNumber(num: Int): MutableList<Int> {
val factors = mutableListOf<Int>()
if (num < 1) return factors
(1..(num / 2))
.filter { num % it == 0 && num / it <= 50 }
.forEach { factors.add(it) }
factors.add(num)
return factors
}
private fun primeFactors(number: Int): ArrayList<Int> {
val arr: ArrayList<Int> = arrayListOf()
var n = number
while (n % 2 == 0) {
arr.add(2)
n /= 2
}
val squareRoot = sqrt(n.toDouble()).toInt()
for (i in 3..squareRoot step 2) {
while (n % i == 0) {
arr.add(i)
n /= i
}
}
if (n > 2) arr.add(n)
return arr
}
}
| 0 | Kotlin | 1 | 3 | 2625719b657eb22c83af95abfb25eb275dbfee6a | 2,041 | advent-of-code | MIT License |
src/main/kotlin/net/hiddevb/advent/advent2019/day05/main.kt | hidde-vb | 224,606,393 | false | null | package net.hiddevb.advent.advent2019.day05
import net.hiddevb.advent.common.initialize
import kotlin.math.floor
/**
* --- Day 5: Sunny with a Chance of Asteroids ---
*/
fun main() {
val fileStrings = initialize("Day 5: Sunny with a Chance of Asteroids", arrayOf("day5.txt"))
println("Part 1: Basic")
val solution1 = solveBasic(fileStrings[0])
println("Solved!\nSolution: $solution1\n")
println("Part 2: Advanced")
val solution2 = solveAdvanced(fileStrings[0])
println("Solved!\nSolution: $solution2\n")
}
// Part 1
fun solveBasic(input: String): Double {
val masses = input.split("\n")
var totalRequiredFuel = 0.0
for (mass in masses) {
if (mass.isNotEmpty()) {
totalRequiredFuel += calculateFuelBasic(mass.toDouble())
}
}
return totalRequiredFuel
}
fun calculateFuelBasic(mass: Double): Double {
return floor(mass / 3) - 2
}
// Part 2
fun solveAdvanced(input: String): Double {
val masses = input.split("\n")
var totalRequiredFuel = 0.0
for (mass in masses) {
if (mass.isNotEmpty()) {
totalRequiredFuel += calculateFuelAdvanced(mass.toDouble())
}
}
return totalRequiredFuel
}
fun calculateFuelAdvanced(mass: Double, acc: Double = 0.0): Double {
val additionalMass = floor(mass / 3) - 2
return when {
additionalMass > 0 -> calculateFuelAdvanced(additionalMass, acc + additionalMass)
else -> return acc
}
} | 0 | Kotlin | 0 | 0 | d2005b1bc8c536fe6800f0cbd05ac53c178db9d8 | 1,481 | advent-of-code-2019 | MIT License |
google/2019/round1_a/3/main.kt | seirion | 17,619,607 | false | {"C++": 801740, "HTML": 42242, "Kotlin": 37689, "Python": 21759, "C": 3798, "JavaScript": 294} | import java.util.*
fun main(args: Array<String>) {
repeat(readLine()!!.toInt()) {
print("Case #${it + 1}: ")
solve()
}
}
fun solve() {
val n = readLine()!!.toInt()
val input = ArrayList<String>()
repeat(n) { input.add(readLine()!!.reversed()) }
input.sort()
val t = Trie('_') // root
input.forEach { t.put(it) }
println("${n - t.unused()}")
}
data class Trie(
val c: Char,
val root: Boolean = (c == '_'),
var terminal: Boolean = false,
val child: ArrayList<Trie> = ArrayList()
) {
fun put(str: String, index: Int = 0) {
val c = str[index]
if (child.isEmpty() || child.last().c != c) {
child.add(Trie(c))
}
if (str.length == index + 1) {
child.last().terminal = true
} else {
child.last().put(str, index + 1)
}
}
fun unused(): Int {
if (child.isEmpty()) return 1
var r = child.map { it.unused() }.sum()
if (terminal) r++
if (!root && r >= 2) r -= 2
return r
}
}
| 0 | C++ | 4 | 4 | a59df98712c7eeceabc98f6535f7814d3a1c2c9f | 1,094 | code | Apache License 2.0 |
src/main/kotlin/Day01.kt | Vampire | 572,990,104 | false | {"Kotlin": 57326} | fun main() {
fun calorySums(caloryList: List<String>): List<Int> {
var calories = 0
val calorySums = caloryList.mapNotNull {
if (it.isEmpty()) {
return@mapNotNull calories.also { calories = 0 }
} else {
calories += it.toInt()
return@mapNotNull null
}
}
return calorySums
}
fun part1(input: List<String>) = calorySums(input).max()
fun part2(input: List<String>) = calorySums(input).sortedDescending().take(3).sum()
val testInput = readStrings("Day01_test")
check(part1(testInput) == 24_000)
val input = readStrings("Day01")
println(part1(input))
check(part2(testInput) == 45_000)
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 16a31a0b353f4b1ce3c6e9cdccbf8f0cadde1f1f | 764 | aoc-2022 | Apache License 2.0 |
solution/#122 Best Time to Buy and Sell Stock II/Solution.kt | enihsyou | 116,918,868 | false | {"Java": 179666, "Python": 36379, "Kotlin": 32431, "Shell": 367} | package leetcode.q122.kotlin;
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
/**
* 122. Best Time to Buy and Sell Stock II
*
* [LeetCode](https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/)
*/
class Solution {
fun maxProfit(prices: IntArray): Int {
if (prices.size < 2) {
return 0
}
var profits = 0
for (day in 1 until prices.size) {
val day1Price = prices[day - 1]
val day2Price = prices[day]
if (isRise(day1Price, day2Price)) {
/* 涨了,就有获利*/
profits += day2Price - day1Price
}
}
return profits
}
private fun isRise(day1: Int, day2: Int) = day1 < day2
class SolutionTest {
private val solution = Solution()
@ParameterizedTest(name = "maxProfit({0}) = {1}")
@MethodSource("provider")
fun maxProfit(input: IntArray, output: Int) {
Assertions.assertEquals(solution.maxProfit(input), output)
}
companion object {
@JvmStatic
fun provider(): List<Arguments> {
return listOf(
Arguments.of(intArrayOf(7, 1, 5, 3, 6, 4), 7),
Arguments.of(intArrayOf(1, 2, 3, 4, 5), 4),
Arguments.of(intArrayOf(7, 6, 4, 3, 1), 0),
Arguments.of(intArrayOf(1), 0),
Arguments.of(intArrayOf(), 0)
)
}
}
}
}
| 1 | Java | 0 | 0 | 230325d1dfd666ee53f304edf74c9c0f60f81d75 | 1,670 | LeetCode | MIT License |
src/main/kotlin/Day02.kt | SimonMarquis | 570,868,366 | false | {"Kotlin": 50263} | class Day02(private val input: List<String>) {
fun part1() = input.sumOf { round ->
when (round) {
"A Y", "B Z", "C X" -> 6 // win
"A X", "B Y", "C Z" -> 3 // draw
"A Z", "B X", "C Y" -> 0 // lose
else -> error(round)
} + (round.last() - 'X').inc()
}
fun part2() = input.sumOf { round ->
val opponent = (round.first() - 'A').inc()
(1..3).reversed()
when (round.last()) {
'Z' -> 6 /* win */ + (opponent % 3) + 1
'Y' -> 3 /* draw */ + opponent
'X' -> 0 /* lose */ + if (opponent == 1) 3 else opponent - 1
else -> error(round)
}
}
}
| 0 | Kotlin | 0 | 0 | a2129cc558c610dfe338594d9f05df6501dff5e6 | 693 | advent-of-code-2022 | Apache License 2.0 |
src/com/mrxyx/algorithm/linked/list/Reverse.kt | Mrxyx | 366,778,189 | false | null | package com.mrxyx.algorithm.linked.list
import com.mrxyx.algorithm.model.ListNode
/**
* 反转链表
*/
class Reverse {
/**
* 反转整个链表
*/
fun reverseAll(head: ListNode): ListNode {
//base case
if (head.next == null) return head
val last = reverseAll(head.next)
head.next.next = head
head.next = null
return last
}
//后继节点
private lateinit var successor: ListNode
/**
* 反转链表前 N 个节点
*/
fun reverseN(head: ListNode, n: Int): ListNode {
if (n == 1) {
successor = head.next
return head
}
val last = reverseN(head.next, n - 1)
head.next.next = head
head.next = successor
return last
}
/**
* 反转链表的一部分
* https://leetcode-cn.com/problems/reverse-linked-list-ii/
*/
fun reverseBetween(head: ListNode, left: Int, right: Int): ListNode {
//base case
if (left == 1) {
return reverseN(head, right)
}
head.next = reverseBetween(head.next, left - 1, right - 1)
return head
}
/**
* 递归反转链表
*/
fun reverse(a: ListNode?): ListNode? {
var pre: ListNode? = null
var cur = a
var nxt: ListNode?
while (cur != null) {
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
}
return pre
}
/**
* 递归反转区间[a,b)
*/
fun reverse(a: ListNode?, b: ListNode?): ListNode? {
var pre: ListNode? = null
var cur = a
var nxt: ListNode?
while (cur != b) {
nxt = cur?.next
cur?.next = pre
pre = cur
cur = nxt
}
return pre
}
/**
* k个一组反转链表
*/
fun reverseKGroup(head: ListNode?, k: Int): ListNode? {
if (head == null) return null
var b = head
for (i in 0..k) {
b = b?.next
}
val newHead = reverse(head, b)
head.next = reverseKGroup(b, k)
return newHead
}
} | 0 | Kotlin | 0 | 0 | b81b357440e3458bd065017d17d6f69320b025bf | 2,181 | algorithm-test | The Unlicense |
src/Day01.kt | gischthoge | 573,509,147 | false | {"Kotlin": 5583} | fun main() {
fun part1(input: List<String>): Int {
return input.splitByBlank().maxOf { elf -> elf.sumOf { it.toInt() } } }
fun part2(input: List<String>): Int {
return input.splitByBlank().map { elf -> elf.sumOf { it.toInt() } }
.sortedDescending()
.take(3)
.sum()
}
val input = readInput("Day01")
println(part1(input))
println(part2(input))
}
fun List<String>.splitByBlank(): List<List<String>> {
// https://stackoverflow.com/questions/65248942/how-to-split-a-list-into-sublists-using-a-predicate-with-kotlin
return this.flatMapIndexed { index: Int, s: String ->
when {
index == 0 || index == this.lastIndex -> listOf(index)
s.isEmpty() || s.isBlank() -> listOf(index - 1, index + 1)
else -> emptyList()
}
}.windowed(size = 2, step = 2) {(from, to) ->
this.slice(from..to)
}
} | 0 | Kotlin | 0 | 0 | e403f738572360d4682f9edb6006d81ce350ff9d | 945 | aock | Apache License 2.0 |
src/year2023/day09/Day.kt | tiagoabrito | 573,609,974 | false | {"Kotlin": 73752} | package year2023.day09
import year2023.solveIt
fun main() {
val day = "09"
val expectedTest1 = 114L
val expectedTest2 = 2L
fun solveIt(values: List<Long>): Long {
if (values.all { it == 0L }) {
return 0L;
}
val rest = solveIt(values.zipWithNext { a, b -> b - a })
return values.last() + rest
}
fun part1(input: List<String>): Long {
return input.map { it.split(" ").map { n -> n.toLong() } }.sumOf { solveIt(it) }
}
fun part2(input: List<String>): Long {
return input.map { it.split(" ").map { n -> n.toLong() } }.sumOf { solveIt(it.reversed()) }
}
solveIt(day, ::part1, expectedTest1, ::part2, expectedTest2, "test")
}
| 0 | Kotlin | 0 | 0 | 1f9becde3cbf5dcb345659a23cf9ff52718bbaf9 | 733 | adventOfCode | Apache License 2.0 |
src/main/kotlin/aoc2022/Day03.kt | davidsheldon | 565,946,579 | false | {"Kotlin": 161960} | package aoc2022
import utils.InputUtils
fun main() {
val testInput = """<KEY>""".split("\n")
fun inHalf(s: String) = (s.length / 2).let { split -> s.substring(0, split) to s.substring(split) }
fun Char.score() = when (this) {
in 'a'..'z' -> 1 + (this - 'a')
in 'A'..'Z' -> 27 + (this - 'A')
else -> -1
}
fun <T> Iterable<Set<T>>.intersectAll() = reduce {a, b -> a.intersect(b) }
fun Iterable<String>.scoreSingleCommonCharacter() = map(String::toSet).intersectAll().first().score()
fun part1(input: List<String>): Int = input.sumOf {
inHalf(it).toList().scoreSingleCommonCharacter()
}
fun part2(input: List<String>) = input.chunked(3).sumOf(List<String>::scoreSingleCommonCharacter)
// test if implementation meets criteria from the description, like:
val testValue = part1(testInput)
println(testValue)
check(testValue == 157)
val puzzleInput = InputUtils.downloadAndGetLines(2022, 3)
val input = puzzleInput.toList()
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | 5abc9e479bed21ae58c093c8efbe4d343eee7714 | 1,221 | aoc-2022-kotlin | Apache License 2.0 |
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions68.kt | qiaoyuang | 100,944,213 | false | {"Kotlin": 338134} | package com.qiaoyuang.algorithm.round0
/**
* 题目:给出两个树的节点,求这两个节点的公共子节点
* 本题根据给出的具体条件的不同则解法也不同,例如,树是否是二叉树,
* 是否是二叉搜索树,每个节点是否包含指向父节点的引用等,
* 为了编程方便,以及难度又较高,我给出的解法为,适用于该树是二叉树,
* 但是不是二叉搜索树,子节点也没有指向父节点的引用。
*/
fun test68() {
val a = BinaryTreeNode('A')
val b = BinaryTreeNode('B')
val c = BinaryTreeNode('C')
val d = BinaryTreeNode('D')
val e = BinaryTreeNode('E')
val f = BinaryTreeNode('F')
val g = BinaryTreeNode('G')
val h = BinaryTreeNode('H')
val i = BinaryTreeNode('I')
val j = BinaryTreeNode('J')
a.left = b
a.right = c
b.left = d
b.right = e
d.left = f
d.right = g
e.left = h
e.right = i
i.right = j
println(a.getLastCommonParent(g, j).value)
println(a.getLastCommonParent(h, j).value)
println(a.getLastCommonParent(f, c).value)
}
fun <T> BinaryTreeNode<T>.getLastCommonParent(
node1: BinaryTreeNode<T>,
node2: BinaryTreeNode<T>
): BinaryTreeNode<T> {
fun BinaryTreeNode<T>.myPreOrder(node: BinaryTreeNode<T>): NodeAndIsFound<T> {
val thisNode = Node<BinaryTreeNode<T>>(this)
if (this === node)
return NodeAndIsFound(thisNode, true)
var left: NodeAndIsFound<T>? = null
this.left?.let {
val myNode = Node<BinaryTreeNode<T>>(it)
val next = it.myPreOrder(node)
myNode.next = next.node
left = NodeAndIsFound(myNode, next.isFound)
}
var right: NodeAndIsFound<T>? = null
this.right?.let {
val myNode = Node<BinaryTreeNode<T>>(it)
val next = it.myPreOrder(node)
myNode.next = next.node
right = NodeAndIsFound(myNode, next.isFound)
}
left?.let {
if (it.isFound) {
thisNode.next = it.node
return NodeAndIsFound(thisNode, it.isFound)
}
}
right?.let {
if (it.isFound) {
thisNode.next = it.node
return NodeAndIsFound(thisNode, it.isFound)
}
}
return NodeAndIsFound(thisNode)
}
var pNode1: Node<BinaryTreeNode<T>>? = myPreOrder(node1).node
var pNode2: Node<BinaryTreeNode<T>>? = myPreOrder(node2).node
lateinit var result: BinaryTreeNode<T>
while (true) {
if (pNode1?.next?.t === pNode2?.next?.t) {
pNode1 = pNode1?.next
pNode2 = pNode2?.next
} else {
result = pNode1?.t!!
break
}
}
return result
}
data class NodeAndIsFound<T>(val node: Node<BinaryTreeNode<T>>, val isFound: Boolean = false) | 0 | Kotlin | 3 | 6 | 66d94b4a8fa307020d515d4d5d54a77c0bab6c4f | 2,512 | Algorithm | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/ReverseLinkedList2.kt | ashtanko | 203,993,092 | false | {"Kotlin": 5856223, "Shell": 1168, "Makefile": 917} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 92. Reverse Linked List II
* @see <a href="https://leetcode.com/problems/reverse-linked-list-ii/">Source</a>
*/
fun interface ReverseLinkedList2 {
fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode?
}
class ReverseLinkedList2Recursive : ReverseLinkedList2 {
// Object level variables since we need the changes
// to persist across recursive calls and Java is pass by value.
private var stop = false
private var left: ListNode? = null
private fun recurseAndReverse(head: ListNode?, m: Int, n: Int) {
// base case. Don't proceed any further
var right: ListNode? = head
if (n == 1) {
return
}
// Keep moving the right pointer one step forward until (n == 1)
right = right?.next
// Keep moving left pointer to the right until we reach the proper node
// from where the reversal is to start.
if (m > 1) {
left = left?.next
}
// Recurse with m and n reduced.
recurseAndReverse(right, m - 1, n - 1)
// In case both the pointers cross each other or become equal, we
// stop i.e. don't swap data any further. We are done reversing at this
// point.
if (left == right || right?.next == left) {
stop = true
}
// Until the boolean stop is false, swap data between the two pointers
if (!stop) {
val leftValue: Int = left?.value ?: 0
this.left?.value = right?.value ?: 0
right?.value = leftValue
// Move left one step to the right.
// The right pointer moves one step back via backtracking.
left = left?.next
}
}
override fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
if (head == null) return null
this.left = head
this.recurseAndReverse(head, left, right)
return head
}
}
class ReverseLinkedList2Iterative : ReverseLinkedList2 {
override fun reverseBetween(head: ListNode?, left: Int, right: Int): ListNode? {
var m = left
var n = right
var node: ListNode? = head
// Move the two pointers until they reach the proper starting point
// in the list.
var cur = node
var prev: ListNode? = null
while (m > 1) {
prev = cur
cur = cur?.next
m--
n--
}
// The two pointers that will fix the final connections.
val con = prev
val tail = cur
// Iteratively reverse the nodes until n becomes 0.
var third: ListNode?
while (n > 0) {
third = cur?.next
cur?.next = prev
prev = cur
cur = third
n--
}
// Adjust the final connections as explained in the algorithm
if (con != null) {
con.next = prev
} else {
node = prev
}
tail?.next = cur
return node
}
}
| 4 | Kotlin | 0 | 19 | 776159de0b80f0bdc92a9d057c852b8b80147c11 | 3,684 | kotlab | Apache License 2.0 |
kotlin/src/main/kotlin/com/pbh/soft/day15/Day15Solver.kt | phansen314 | 579,463,173 | false | {"Kotlin": 105902} | package com.pbh.soft.day15
import com.pbh.soft.common.Solver
import com.pbh.soft.common.parsing.ParsingUtils.onSuccess
import com.pbh.soft.day15.Op.Del
import com.pbh.soft.day15.Op.Ins
import com.pbh.soft.kparse.KParser
import com.pbh.soft.kparse.KParser.Companion.chr
import com.pbh.soft.kparse.KParser.Companion.intNum
import com.pbh.soft.kparse.KParser.Companion.keepR
import com.pbh.soft.kparse.KParser.Companion.manySep
import com.pbh.soft.kparse.KParser.Companion.map
import com.pbh.soft.kparse.KParser.Companion.or
import com.pbh.soft.kparse.KParser.Companion.parser
import mu.KLogging
object Day15Solver : Solver, KLogging() {
override fun solveP1(text: String): String = Parsing.problemP.onSuccess(text) { steps ->
val answer = steps.sumOf { it.hash() }
return "$answer"
}
override fun solveP2(text: String): String = Parsing.problemP.onSuccess(text) { steps ->
val labelXboxId = mutableMapOf<Label, BoxId>(); steps.associate { it.label to it.label.hash() as BoxId }
val boxIdXLenses = mutableMapOf<BoxId, ArrayList<Step>>()
for (step in steps) {
val boxId = labelXboxId.getOrPut(step.label) { step.label.hash() }
val lenses = boxIdXLenses.getOrPut(boxId, ::ArrayList)
when (step.op) {
Del -> lenses.remove(step)
is Ins -> {
val idx = lenses.indexOf(step)
if (idx == -1) lenses.add(step)
else lenses[idx] = step
}
}
}
val answer = boxIdXLenses.asSequence()
.map { (it.key + 1) * it.value.foldIndexed(0) { index, acc, step -> acc + (index + 1) * (step.op as Ins).focalLength } }
.sum()
return "$answer"
}
private fun Step.hash(): Int {
val total = label.hash(0)
return when (op) {
Del -> '-'.hash(total)
is Ins -> {
op.focalLength.digitToChar().hash('='.hash(total))
}
}
}
private fun String.hash(input: Int = 0): Int {
var total = input
for (c: Int in chars()) {
total += c
total *= 17
total %= 256
}
return total
}
private fun Char.hash(input: Int = 0): Int {
var total = input + code
total *= 17
total %= 256
return total
}
fun Step.pprint(): String = when (op) {
Del -> "$label-"
is Ins -> "$label=${op.focalLength}"
}
}
typealias Label = String
typealias BoxId = Int
sealed class Op {
data object Del : Op()
data class Ins(val focalLength: Int) : Op()
}
class Step(val label: Label, val op: Op) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Step) return false
return label == other.label
}
override fun hashCode(): Int {
return label.hashCode()
}
override fun toString(): String = when (op) {
Del -> "$label-"
is Ins -> "$label=${op.focalLength}"
}
}
object Parsing {
val delOpP: KParser<Op> = chr('-').map { Del }
val insOpP: KParser<Op> = chr('=').keepR(intNum).map { Ins(it) }
val opP = delOpP.or(insOpP)
val stepP = parser {
val label = Regex("[^,=-]*")()
val op = opP()
Step(label, op)
}
val problemP = stepP.manySep(chr(',')).map { it.values }
} | 0 | Kotlin | 0 | 0 | 7fcc18f453145d10aa2603c64ace18df25e0bb1a | 3,131 | advent-of-code | MIT License |
src/main/kotlin/aoc2020/CrabCups.kt | komu | 113,825,414 | false | {"Kotlin": 395919} | package komu.adventofcode.aoc2020
fun crabCups1(labels: String) =
crapCups(labels, iterations = 100, maxLabel = 9).answer()
fun crabCups2(labels: String): Long {
val one = crapCups(labels, iterations = 10_000_000, maxLabel = 1_000_000)
return one.next.label.toLong() * one.next.next.label
}
private fun crapCups(labels: String, iterations: Int, maxLabel: Int): CupCircleNode {
val first = CupCircleNode.build(labels, maxLabel)
val nodesByLabels = Array(maxLabel + 1) { first }
for (node in first)
nodesByLabels[node.label] = node
var current = first
repeat(iterations) {
val firstRemoved = current.next
val lastRemoved = firstRemoved.next.next
val afterLast = lastRemoved.next
current.next = afterLast
val destinationLabel = pickDestinationLabel(current.label - 1, firstRemoved, maxLabel)
val destination = nodesByLabels[destinationLabel]
val next = destination.next
destination.next = firstRemoved
lastRemoved.next = next
current = current.next
}
return nodesByLabels[1]
}
private fun pickDestinationLabel(firstCandidate: Int, firstRemoved: CupCircleNode, maxLabel: Int): Int {
val illegal1 = firstRemoved.label
val illegal2 = firstRemoved.next.label
val illegal3 = firstRemoved.next.next.label
var value = if (firstCandidate == 0) maxLabel else firstCandidate
while (value == illegal1 || value == illegal2 || value == illegal3)
value = if (value == 1) maxLabel else (value - 1)
return value
}
private class CupCircleNode(val label: Int) : Iterable<CupCircleNode> {
lateinit var next: CupCircleNode
override fun iterator() = iterator {
val first = this@CupCircleNode
var node = first
do {
yield(node)
node = node.next
} while (node != first)
}
fun answer() =
drop(1).map { it.label }.joinToString("")
companion object {
fun build(labelString: String, maxLabel: Int): CupCircleNode {
val givenLabels = labelString.map { it.toString().toInt() }
val first = CupCircleNode(givenLabels.first())
var previous = first
for (cup in givenLabels.drop(1)) {
val node = CupCircleNode(cup)
previous.next = node
previous = node
}
for (cup in 10..maxLabel) {
val node = CupCircleNode(cup)
previous.next = node
previous = node
}
previous.next = first
return first
}
}
}
| 0 | Kotlin | 0 | 0 | 8e135f80d65d15dbbee5d2749cccbe098a1bc5d8 | 2,647 | advent-of-code | MIT License |
src/week1/MaxProfit.kt | anesabml | 268,056,512 | false | null | package week1
import kotlin.math.max
import kotlin.math.min
import kotlin.system.measureNanoTime
class MaxProfit {
/** Brute force
* Search for the max profit by calculating the profit between all the elements
* Time complexity : O(n2)
* Space complexity : O(1)
*/
fun maxProfit(prices: IntArray): Int {
var maxprofit = 0
for (i in 0 until prices.size - 1) {
for (j in i + 1 until prices.size) {
val currentProfit = prices[j] - prices[i]
if (currentProfit > maxprofit) maxprofit = currentProfit
}
}
return maxprofit
}
/** Optimization
* So we can get the min price and calculate the profit in the same time
* Time complexity : O(n)
* Space complexity : O(1)
*/
fun maxProfit2(prices: IntArray): Int {
var minPrice = Int.MAX_VALUE
var maxProfit = 0
prices.forEach { currentPrice ->
minPrice = min(minPrice, currentPrice)
maxProfit = max(currentPrice - minPrice, maxProfit)
}
return maxProfit
}
}
fun main() {
val input = intArrayOf(7, 1, 5, 3, 6, 4)
val maxProfit = MaxProfit()
val firstSolutionTime = measureNanoTime { println(maxProfit.maxProfit(input)) }
val secondSolutionTime = measureNanoTime { println(maxProfit.maxProfit2(input)) }
println("First Solution execution time: $firstSolutionTime")
println("Second Solution execution time: $secondSolutionTime")
} | 0 | Kotlin | 0 | 1 | a7734672f5fcbdb3321e2993e64227fb49ec73e8 | 1,513 | leetCode | Apache License 2.0 |
src/main/kotlin/aoc23/Day08.kt | asmundh | 573,096,020 | false | {"Kotlin": 56155} | package aoc23
import lcm
import lcmOfList
import runTask
import utils.InputReader
import java.lang.IllegalStateException
import kotlin.collections.Map
fun day8part1(input: List<String>): Int {
val m = input.toSwampMap()
var current = "AAA"
var index = 0
var moves = 0
while (current != "ZZZ") {
current = when (m.instructions[index++]) {
'L' -> m.maps[current]?.left!!
'R' -> m.maps[current]?.right!!
else -> throw IllegalStateException("What the hell")
}
index %= m.instructions.length
moves ++
}
return moves
}
fun day8part2(input: List<String>): Long {
val swampMap = input.toSwampMap()
val locations = swampMap.maps.keys.filter { it.last() == 'A' }
var index = 0
val goals = mutableListOf<Long>()
locations.forEach {
var current = it
var moves = 0L
while (current.last() != 'Z') {
current = when (swampMap.instructions[index++]) {
'L' -> swampMap.maps[current]?.left!!
'R' -> swampMap.maps[current]?.right!!
else -> throw IllegalStateException("What the hell")
}
index %= swampMap.instructions.length
moves ++
}
goals.add(moves)
}
return lcmOfList(goals)
}
data class SwampMap(
val instructions: String,
val maps: Map<String, Target>
)
data class Target(
val left: String,
val right: String,
)
fun List<String>.toSwampMap(): SwampMap =
SwampMap(
this.first(),
this.drop(2).associate {
val target = it.substring(0, 3)
val left = it.substring(7, 10)
val right = it.substring(12, 15)
target to Target(left, right)
}
)
fun main() {
val input = InputReader.getInputAsList<String>(8)
// runTask("D8P1") { day8part1(input) }
runTask("D8P2") { day8part2(input) }
}
| 0 | Kotlin | 0 | 0 | 7d0803d9b1d6b92212ee4cecb7b824514f597d09 | 1,938 | advent-of-code | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.