Best Mockito-kotlin code snippet using test.Open.intArray
InternalUtilsTest.kt
Source:InternalUtilsTest.kt
...135Inferred types:136 <T> -> Int137'Test' @ [58:5] ==> public constructor Test(expected: KClass<out (Throwable..Throwable?)> = ..., timeout: Long = ...) defined in org.junit.Test[JavaClassConstructorDescriptor]138'assertArrayEquals' @ [60:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]139'intArrayOf' @ [60:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]140'..' @ [60:52] ==> public final operator fun rangeTo(other: Int): IntRange defined in kotlin.Int[DeserializedSimpleFunctionDescriptor]141'stream' @ [60:58] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]142'toArray' @ [60:67] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]143'assertArrayEquals' @ [61:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]144'intArrayOf' @ [61:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]145'until' @ [61:52] ==> public infix fun Int.until(to: Int): IntRange defined in kotlin.ranges[DeserializedSimpleFunctionDescriptor]146'stream' @ [61:63] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]147'toArray' @ [61:72] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]148'assertArrayEquals' @ [62:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]149'intArrayOf' @ [62:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]150'..' @ [62:46] ==> public final operator fun rangeTo(other: Int): IntRange defined in kotlin.Int[DeserializedSimpleFunctionDescriptor]151'stream' @ [62:59] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]152'toArray' @ [62:68] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]153'assertArrayEquals' @ [63:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]154'intArrayOf' @ [63:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]155'..' @ [63:46] ==> public final operator fun rangeTo(other: Int): IntRange defined in kotlin.Int[DeserializedSimpleFunctionDescriptor]156'stream' @ [63:59] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]157'toArray' @ [63:68] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]158'assertArrayEquals' @ [64:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]159'intArrayOf' @ [64:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]160'..' @ [64:42] ==> public final operator fun rangeTo(other: Int): IntRange defined in kotlin.Int[DeserializedSimpleFunctionDescriptor]161'stream' @ [64:48] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]162'toArray' @ [64:57] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]163'assertArrayEquals' @ [65:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]164'intArrayOf' @ [65:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]165'downTo' @ [65:46] ==> public infix fun Int.downTo(to: Int): IntProgression defined in kotlin.ranges[DeserializedSimpleFunctionDescriptor]166'stream' @ [65:58] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]167'toArray' @ [65:67] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]168'assertArrayEquals' @ [66:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]169'intArrayOf' @ [66:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]170'downTo' @ [66:46] ==> public infix fun Int.downTo(to: Int): IntProgression defined in kotlin.ranges[DeserializedSimpleFunctionDescriptor]171'stream' @ [66:65] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]172'toArray' @ [66:74] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]173'assertArrayEquals' @ [67:9] ==> public open fun assertArrayEquals(p0: (IntArray..IntArray?), p1: (IntArray..IntArray?)): Unit defined in org.junit.Assert[JavaMethodDescriptor]174'intArrayOf' @ [67:27] ==> public fun intArrayOf(vararg elements: Int): IntArray defined in kotlin[DeserializedSimpleFunctionDescriptor]175'downTo' @ [67:46] ==> public infix fun Int.downTo(to: Int): IntProgression defined in kotlin.ranges[DeserializedSimpleFunctionDescriptor]176'stream' @ [67:65] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]177'toArray' @ [67:74] ==> public abstract fun toArray(): (IntArray..IntArray?) defined in java.util.stream.IntStream[JavaMethodDescriptor]178'Test' @ [70:5] ==> public constructor Test(expected: KClass<out (Throwable..Throwable?)> = ..., timeout: Long = ...) defined in org.junit.Test[JavaClassConstructorDescriptor]179'range' @ [72:46] ==> public open fun range(p0: Int, p1: Int): (IntStream..IntStream?) defined in java.util.stream.IntStream[JavaMethodDescriptor]180'spliterator' @ [72:58] ==> public abstract fun spliterator(): (Spliterator.OfInt..Spliterator.OfInt?) defined in java.util.stream.IntStream[JavaMethodDescriptor]181'characteristics' @ [72:72] ==> public abstract fun characteristics(): Int defined in java.util.Spliterator.OfInt[JavaMethodDescriptor]182'..' @ [73:24] ==> public final operator fun rangeTo(other: Int): IntRange defined in kotlin.Int[DeserializedSimpleFunctionDescriptor]183'stream' @ [73:37] ==> public fun IntProgression.stream(parallel: Boolean = ...): IntStream defined in net.corda.core.internal[DeserializedSimpleFunctionDescriptor]184'spliterator' @ [73:46] ==> public abstract fun spliterator(): (Spliterator.OfInt..Spliterator.OfInt?) defined in java.util.stream.IntStream[JavaMethodDescriptor]185'assertEquals' @ [74:9] ==> public fun <@OnlyInputTypes T> assertEquals(expected: Int, actual: Int, message: String? = ...): Unit defined in kotlin.test[DeserializedSimpleFunctionDescriptor]186Inferred types:187 <@OnlyInputTypes T> -> Int188'rangeCharacteristics' @ [74:22] ==> val rangeCharacteristics: Int defined in net.corda.core.internal.InternalUtilsTest.`IntProgression spliterator characteristics and comparator`[LocalVariableDescriptor]...
KTest.kt
Source:KTest.kt
...65 var left: TreeNode? = null66 var right: TreeNode? = null67 }68 fun findMode(root: TreeNode?): IntArray {69 if (root == null) return intArrayOf()70 val map = mutableMapOf<Int, Int>()71 val resList = mutableListOf<Int>()72 dfs(root, resList)73 return resList.toIntArray()74 }75 var preVal = 076 var curCount = 077 var maxCount = 078 fun dfs(node: KTest.TreeNode?, list: MutableList<Int>) {79 if (node == null) return80 dfs(node.left, list)81 if (preVal == node.`val`) {82 curCount++83// maxCount = max(curCount,maxCount)84 } else {85 preVal = node.`val`86 curCount = 187 }88 if (maxCount == curCount) {89 list.add(node.`val`)90 } else if (curCount > maxCount) {91 maxCount = curCount92 list.clear()93 list.add(node.`val`)94 }95 dfs(node.right, list)96 }97 var postIndex = 098 fun buildTree(inorder: IntArray, postorder: IntArray): TreeNode? {99 val midIndexMap = mutableMapOf<Int, Int>()100 inorder.forEachIndexed { index: Int, i: Int ->101 midIndexMap[i] = index102 }103 val len = inorder.size - 1104 postIndex = len105 return buildTree(inorder, postorder, 0, len, midIndexMap)106 }107 private fun buildTree(inorder: IntArray, postorder: IntArray, preStart: Int, preEnd: Int, indexMap: MutableMap<Int, Int>): TreeNode? {108 if (postIndex < 0 || preStart > preEnd) return null109 val indexOrderIndex = indexMap[postorder[postIndex]] ?: return null110 val treeNode = TreeNode(inorder[indexOrderIndex])111// var pIndex = postIndex112 postIndex--113 treeNode.right = buildTree(inorder, postorder, indexOrderIndex + 1, preEnd, indexMap)114 treeNode.left = buildTree(inorder, postorder, preStart, indexOrderIndex - 1, indexMap)115 return treeNode116 }117 fun exist(board: Array<CharArray>, word: String): Boolean {118 if (board.isEmpty()) return false119 if (word.isEmpty()) return true120 val m = board.size121 val n = board[0].size122 board.forEachIndexed { mIndex, mChars ->123 mChars.forEachIndexed { nIndex, nChars ->124 if (exist(board, word, 0, mIndex, nIndex, m, n)) return true125 }126 }127 return false128 }129 private fun exist(board: Array<CharArray>, word: String, wIndex: Int, x: Int, y: Int, m: Int, n: Int): Boolean {130 if (wIndex >= word.length) return true131 if (x < 0 || x >= m || y < 0 || y >= n) return false132 if (word[wIndex] != board[x][y] || board[x][y] == '-') return false133 val c = board[x][y]134 board[x][y] = '-'135 val res = exist(board, word, wIndex, x, y, m, n) || exist(board, word, wIndex, x, y, m, n)136 || exist(board, word, wIndex, x, y, m, n) || exist(board, word, wIndex, x, y, m, n)137 board[x][y] = c138 return res139 }140 @Test141 fun testKobj() {142 val kObj = KObj<Int>()143 kObj.obj = 10144 kObj.init {145 println(it)146 }147 println(measureTimeMillis {148 val json = "{\"priorityList\":[{\"adSourceType\":0,\"priority\":1,\"weight\":0},{\"adSourceType\":2,\"priority\":1,\"weight\":100}],\"rcode\":0}"149 val data = Gson().fromJson(json, ThirdAdPriorityResponse::class.java)150 println(data.priorityList)151 })152 }153 data class ThirdAdPriorityResponse(val rcode: Int, val priorityList: List<ThirdAdPriority>)154 data class ThirdAdPriority(155 /**156 * 广åæºï¼0为èæç´æï¼1为å®æ¶apiï¼2为sdk157 */158 val adSourceType: Int,159 /**160 * 广åæºä¼å
级ï¼ä¼å
å¤æä¼å
级ï¼ä¼å
级ä¸æ ·åå¤ææéï¼è¶å°è¶ä¼å
161 */162 val priority: Int,163 /**164 * 广åæºæéï¼ä¼å
级ä¸æ ·æ¶ä½¿ç¨165 */166 val weight: Int167 )168 fun sortedSquares(A: IntArray): IntArray {169 val res = IntArray(A.size)170 var resIndex = 0171 var start = 0172 var end = A.size - 1173 while (resIndex < A.size) {174 if (Math.abs(A[start]) > Math.abs(A[end])) {175 res[resIndex++] = Math.pow(A[start++].toDouble(), 2.0).toInt()176 } else {177 res[resIndex++] = Math.pow(A[end--].toDouble(), 2.0).toInt()178 }179 }180 return res181 }182 fun backspaceCompare(S: String, T: String): Boolean {183 val sChars = mutableListOf<Char>()184 return false185 }186 @Test187 fun testBreak() {188 val listOf = listOf<Int>(1, 2, 3, 4)189 listOf.forEach Fuck@{190 if (it == 3) return191 println(it)192 }193 println("finish")194 }195 fun sortByBits(arr: IntArray): IntArray {196 val bitMap = IntArray(10001)197 for (i in 1..bitMap.size) {198 bitMap[i] = bitMap[i shr 1] + bitMap[i] and 1199 }200 return arr.sortedWith(Comparator<Int> { o1, o2 ->201 bitMap[o1] - bitMap[o2]202 }).toIntArray()203 }204 fun compute(data: Collection<Int>): Int {205// Logz.tag(IDecision.TAG).d("LzSplashDecision#start compute in:$data")206 val priorityMap = mResponseData!!.priorityList.groupBy { it.priority }207 val sortedPriorityList = priorityMap.keys.sorted()208 var res = -1209 // æ ¹æ®ä¼å
级ä½ç顺åºåï¼åå°ç´æ¥è¿å210 sortedPriorityList.forEach {211 if (res != -1) {212 return@forEach213 }214 val weightList = priorityMap[it]215 // å½å½åä¼å
级ç¸åæ°é大äº1æ¶ï¼å
å»é¤å¹¿åæ°æ®ä¸åå¨ç广åç±»åé
ç½®216 if (weightList?.size!! > 1) {217 var l = weightList.toMutableList()218 l.filter { thirdAdPriority ->219 !data.contains(thirdAdPriority.adSourceType)220 }221 // æ ¹æ®æéæ¯ç®åºè¦å±ç¤ºåªä¸ª222 val predictionValue = Random.nextFloat()223 val totalWeight = l.sumBy { thirdAdPriority -> thirdAdPriority.weight }224 var curValue = 0f225 l.forEach { thirdAdPriority ->226 val pre = curValue227 curValue += thirdAdPriority.weight.div(totalWeight.toFloat())228 if (pre <= predictionValue && predictionValue < curValue) {229 res = thirdAdPriority.adSourceType230 }231 }232 } else if (data.contains(weightList[0].adSourceType)) {233 res = weightList[0].adSourceType234 }235 }236// Logz.tag(IDecision.TAG).w("LzSplashDecision#compute show splash type is $res")237 return res238 }239 var mResponseData: ThirdAdPriorityResponse? = null240 @Test241 fun computeTest() {242 val json = "{\"priorityList\":[{\"adSourceType\":0,\"priority\":1,\"weight\":100},{\"adSourceType\":1,\"priority\":3,\"weight\":100},{\"adSourceType\":2,\"priority\":3,\"weight\":100}],\"rcode\":0}"243 mResponseData = Gson().fromJson(json, ThirdAdPriorityResponse::class.java)244 println(mResponseData?.priorityList)245 println(compute(listOf(1, 2)))246 }247 fun reconstructQueue(people: Array<IntArray>): Array<IntArray> {248 people.sortWith(compareBy({ it[0] }, { it[1] }))249 val res = arrayOfNulls<IntArray>(people.size)250 people.forEach {251 var pre = it[1]252 run out@{253 people.forEachIndexed{index,value->254 if(pre == 0 && res[index]?.isEmpty() != false){255 res[index] = it256 return@out257 }else if(pre > 0){258 pre--259 }260 }261 }262 }263 return res.requireNoNulls()264 }265 fun moveZeroes(nums: IntArray): Unit {266 val last = nums.size - 1267 for (i in last downTo 0){268 if(nums[i] == 0){269 var tempI = i270 while(tempI < last){271 if(nums[tempI + 1] == 0)break272 val t = nums[tempI]273 nums[tempI] = nums[tempI + 1]274 nums[tempI + 1] = t275 }276 }277 }278 }279 fun searchRange(nums: IntArray, target: Int): IntArray {280 var resStartPos = -1281 var resEndPos = -1282 var start = 0283 var end = nums.size - 1284 while(start <= end){285 val mid = start + (end - start)/2286 if(nums[mid] == target){287 resStartPos = mid288 resEndPos = mid289 break290 }else if(nums[mid] < target){291 start = mid + 1292 }else{293 end = mid - 1294 }295 }296 if(resStartPos != -1 && nums[resStartPos - 1] == target){297 resStartPos--298 }299 if(resEndPos != -1 && nums[resEndPos + 1] == target){300 resEndPos++301 }302 return intArrayOf(resStartPos,resEndPos)303 }304 fun lemonadeChange(bills: IntArray): Boolean {305 val billMap = mutableMapOf<Int,Int>()306 bills.forEach {307 var rest = it - 5308 while(rest > 0){309 }310 billMap[it] = billMap[it]?:0.plus(1)311 }312 return true313 }314 class Resp{315 fun show(){316 }...
SampleTests.kt
Source:SampleTests.kt
1import org.jsuffixarrays.*2import kotlin.random.Random3import kotlin.test.*4/**5 * A set of shared tests and preconditions that all implementations of6 * [ISuffixArrayBuilder] should meet.7 */8abstract class LinuxSuffixArrayBuilderTestBase {9 lateinit var builder: ISuffixArrayBuilder10 var smallAlphabet: MinMax = MinMax(-5, 5)11 var largeAlphabet: MinMax = MinMax(-500, 500)12 /**13 * Subclasses must override and return a valid instance of [ISuffixArrayBuilder]14 * .15 */16 protected abstract val instance: ISuffixArrayBuilder17 @BeforeTest18 fun prepareBuilder() {19 builder = instance20 }21 /**22 * Check the suffixes of `banana`.23 */24 @Test25 fun checkBanana() {26 assertSuffixes("banana", "a", "ana", "anana", "banana", "na", "nana")27 }28 /**29 * Check the suffixes of `mississippi`.30 */31 @Test32 fun checkMississippi() {33 assertSuffixes("mississippi", "i", "ippi", "issippi", "ississippi",34 "mississippi", "pi", "ppi", "sippi", "sissippi", "ssippi", "ssissippi")35 }36 /**37 * Create a suffix array for the same input sequence, but placed at different offsets38 * in the input array. The result should be identical (not counting the offset of39 * course).40 *41 *42 * Checks the LCP array created for the given input as well.43 */44 @Test45 open fun sameResultWithArraySlice() {46 val builder = instance47 val sliceSize = 50048 val totalSize = 100049 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE50 val rnd = Random(0x11223344)51 val alphabet = MinMax(1, 50)52 val slice = generateRandom(rnd, sliceSize, alphabet)53 val total = generateRandom(rnd, totalSize + extraSpace, alphabet)54 var prevSuffixArray: IntArray? = null55 var prevLCP: IntArray? = null56 for (i in 0 until totalSize - slice.size) {57 val input = total.copyOf()58 arraycopy(slice, 0, input, i, slice.size)59 val clone = input.clone()60 val sa = builder.buildSuffixArray(input, i, slice.size)61 val lcp = SuffixArrays.computeLCP(input, i, slice.size, sa)62 assertEquals(clone.toList(), input.toList())63 if (prevSuffixArray != null) {64 assertEquals(prevSuffixArray.toList(), sa.toList())65 }66 prevSuffixArray = sa67 // Compare LCPs68 if (prevLCP != null) {69 assertEquals(prevLCP.toList(), lcp.toList())70 }71 prevLCP = lcp72 }73 }74 /**75 * Create suffix arrays for a few random sequences of integers, verify invariants76 * (every suffix array is a permutation of indices, every suffix in the suffix array77 * is lexicographically greater or equal than all its predecessors).78 */79 @Test80 fun invariantsOnRandomSmallAlphabet() {81 val builder = instance82 // Use constant seed so that we can repeat tests.83 val rnd = Random(0x11223344)84 val inputSize = 100085 val repeats = 50086 runRandom(builder, rnd, inputSize, repeats, smallAlphabet)87 }88 /**89 * @see .invariantsOnRandomSmallAlphabet90 */91 @Test92 open fun invariantsOnRandomLargeAlphabet() {93 val builder = instance94 // Use constant seed so that we can repeat tests.95 val rnd = Random(0x11223344)96 val inputSize = 100097 val repeats = 50098 runRandom(builder, rnd, inputSize, repeats, largeAlphabet)99 }100 /*101 * Run invariant checks on randomly generated data.102 */103 private fun runRandom(builder: ISuffixArrayBuilder, rnd: Random,104 inputSize: Int, repeats: Int, alphabet: MinMax) {105 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE106 for (i in 0 until repeats) {107 val input = generateRandom(rnd, inputSize + extraSpace, alphabet)108 val copy = input.clone()109 val start = 0110 val SA = builder.buildSuffixArray(input, start, inputSize)111 assertEquals( input.toList(), copy.toList())112 assertPermutation(SA, inputSize)113 assertSorted(SA, input, inputSize)114 }115 }116 /*117 * Verify that two suffixes are less or equal.118 */119 private fun sleq(s1: IntArray, s1i: Int, s2: IntArray, s2i: Int, n: Int): Boolean {120 var s1i = s1i121 var s2i = s2i122 do {123 if (s1[s1i] < s2[s2i]) return true124 if (s1[s1i] > s2[s2i]) return false125 s2i++126 s1i++127 if (s1i == n) return true128 } while (true)129 }130 /*131 * Make sure suffixes in a suffix array are sorted.132 */133 private fun assertSorted(SA: IntArray, s: IntArray, n: Int) {134 for (i in 0 until n - 1) {135 if (!sleq(s, SA[i], s, SA[i + 1], n)) {136 fail("Suffix " + SA[i] + ">" + SA[i + 1] + ":\n" + SA[i] + ">"137 + s.slice(SA[i]until n) + "\n" + SA[i + 1]138 + ">" + s.slice (SA[i + 1].. n) + "\n" + "a>"139 + s.asList( ))140 }141 }142 }143 /*144 * Assert a suffix array is a permutation of indices.145 */146 private fun assertPermutation(SA: IntArray, length: Int) {147 val seen = BooleanArray(length)148 for (i in 0 until length) {149 assertFalse(seen[SA[i]])150 seen[SA[i]] = true151 }152 for (i in 0 until length) {153 assertTrue(seen[i])154 }155 }156 /*157 * Assert a suffix array built for a given input contains exactly the given set of158 * suffixes, in that order.159 */160 private fun assertSuffixes(input: CharSequence, vararg expectedSuffixes: CharSequence) {161 val suffixes = SuffixArrays.create(input, instance)162 assertEquals(expectedSuffixes.asList( ), SuffixArrays.toString(input,163 suffixes))164 }165 companion object {166 /*167 * Generate random data.168 */169 fun generateRandom(rnd: Random, size: Int, alphabet: MinMax): IntArray {170 val input = IntArray(size)171 fillRandom(rnd, input, size, alphabet)172 return input173 }174 /*175 * Fill an array with random symbols from the given alphabet/176 */177 fun fillRandom(rnd: Random, input: IntArray, size: Int, alphabet: MinMax) {178 for (j in input.indices) {179 input[j] = rnd.nextInt(alphabet.range() + 1) + alphabet.min180 }181 }182 }183}184private fun IntArray.clone(): IntArray =copyOf()185/**186 * Tests for [DivSufSort].187 */188class LinuxDivSufSortTest : SuffixArrayBuilderTestBase() {189 private val alphabetSize = 256190 /*191 *192 */193 override val instance: ISuffixArrayBuilder194 get() = DivSufSort(alphabetSize)195 @BeforeTest196 fun setupForConstraints() {197 smallAlphabet=(MinMax(1, 10))198 largeAlphabet=(MinMax(1, alphabetSize - 1))199 }200}...
JvmSampleTests.kt
Source:JvmSampleTests.kt
1import org.jsuffixarrays.*2import kotlin.random.Random3import kotlin.test.*4/**5 * A set of shared tests and preconditions that all implementations of6 * [ISuffixArrayBuilder] should meet.7 */8abstract class JvmSuffixArrayBuilderTestBase {9 lateinit var builder: ISuffixArrayBuilder10 var smallAlphabet: MinMax = MinMax(-5, 5)11 var largeAlphabet: MinMax = MinMax(-500, 500)12 /**13 * Subclasses must override and return a valid instance of [ISuffixArrayBuilder]14 * .15 */16 protected abstract val instance: ISuffixArrayBuilder17 @BeforeTest18 fun prepareBuilder() {19 builder = instance20 }21 /**22 * Check the suffixes of `banana`.23 */24 @Test25 fun checkBanana() {26 assertSuffixes("banana", "a", "ana", "anana", "banana", "na", "nana")27 }28 /**29 * Check the suffixes of `mississippi`.30 */31 @Test32 fun checkMississippi() {33 assertSuffixes("mississippi", "i", "ippi", "issippi", "ississippi",34 "mississippi", "pi", "ppi", "sippi", "sissippi", "ssippi", "ssissippi")35 }36 /**37 * Create a suffix array for the same input sequence, but placed at different offsets38 * in the input array. The result should be identical (not counting the offset of39 * course).40 *41 *42 * Checks the LCP array created for the given input as well.43 */44 @Test45 open fun sameResultWithArraySlice() {46 val builder = instance47 val sliceSize = 50048 val totalSize = 100049 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE50 val rnd = Random(0x11223344)51 val alphabet = MinMax(1, 50)52 val slice = generateRandom(rnd, sliceSize, alphabet)53 val total = generateRandom(rnd, totalSize + extraSpace, alphabet)54 var prevSuffixArray: IntArray? = null55 var prevLCP: IntArray? = null56 for (i in 0 until totalSize - slice.size) {57 val input = total.copyOf()58 arraycopy(slice, 0, input, i, slice.size)59 val clone = input.clone()60 val sa = builder.buildSuffixArray(input, i, slice.size)61 val lcp = SuffixArrays.computeLCP(input, i, slice.size, sa)62 assertEquals(clone.toList(), input.toList())63 if (prevSuffixArray != null) {64 assertEquals(prevSuffixArray.toList(), sa.toList())65 }66 prevSuffixArray = sa67 // Compare LCPs68 if (prevLCP != null) {69 assertEquals(prevLCP.toList(), lcp.toList())70 }71 prevLCP = lcp72 }73 }74 /**75 * Create suffix arrays for a few random sequences of integers, verify invariants76 * (every suffix array is a permutation of indices, every suffix in the suffix array77 * is lexicographically greater or equal than all its predecessors).78 */79 @Test80 fun invariantsOnRandomSmallAlphabet() {81 val builder = instance82 // Use constant seed so that we can repeat tests.83 val rnd = Random(0x11223344)84 val inputSize = 100085 val repeats = 50086 runRandom(builder, rnd, inputSize, repeats, smallAlphabet)87 }88 /**89 * @see .invariantsOnRandomSmallAlphabet90 */91 @Test92 open fun invariantsOnRandomLargeAlphabet() {93 val builder = instance94 // Use constant seed so that we can repeat tests.95 val rnd = Random(0x11223344)96 val inputSize = 100097 val repeats = 50098 runRandom(builder, rnd, inputSize, repeats, largeAlphabet)99 }100 /*101 * Run invariant checks on randomly generated data.102 */103 private fun runRandom(builder: ISuffixArrayBuilder, rnd: Random,104 inputSize: Int, repeats: Int, alphabet: MinMax) {105 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE106 for (i in 0 until repeats) {107 val input = generateRandom(rnd, inputSize + extraSpace, alphabet)108 val copy = input.clone()109 val start = 0110 val SA = builder.buildSuffixArray(input, start, inputSize)111 assertEquals( input.toList(), copy.toList())112 assertPermutation(SA, inputSize)113 assertSorted(SA, input, inputSize)114 }115 }116 /*117 * Verify that two suffixes are less or equal.118 */119 private fun sleq(s1: IntArray, s1i: Int, s2: IntArray, s2i: Int, n: Int): Boolean {120 var s1i = s1i121 var s2i = s2i122 do {123 if (s1[s1i] < s2[s2i]) return true124 if (s1[s1i] > s2[s2i]) return false125 s2i++126 s1i++127 if (s1i == n) return true128 } while (true)129 }130 /*131 * Make sure suffixes in a suffix array are sorted.132 */133 private fun assertSorted(SA: IntArray, s: IntArray, n: Int) {134 for (i in 0 until n - 1) {135 if (!sleq(s, SA[i], s, SA[i + 1], n)) {136 fail("Suffix " + SA[i] + ">" + SA[i + 1] + ":\n" + SA[i] + ">"137 + s.slice(SA[i]until n) + "\n" + SA[i + 1]138 + ">" + s.slice (SA[i + 1].. n) + "\n" + "a>"139 + s.asList( ))140 }141 }142 }143 /*144 * Assert a suffix array is a permutation of indices.145 */146 private fun assertPermutation(SA: IntArray, length: Int) {147 val seen = BooleanArray(length)148 for (i in 0 until length) {149 assertFalse(seen[SA[i]])150 seen[SA[i]] = true151 }152 for (i in 0 until length) {153 assertTrue(seen[i])154 }155 }156 /*157 * Assert a suffix array built for a given input contains exactly the given set of158 * suffixes, in that order.159 */160 private fun assertSuffixes(input: CharSequence, vararg expectedSuffixes: CharSequence) {161 val suffixes = SuffixArrays.create(input, instance)162 assertEquals(expectedSuffixes.asList( ), SuffixArrays.toString(input,163 suffixes))164 }165 companion object {166 /*167 * Generate random data.168 */169 fun generateRandom(rnd: Random, size: Int, alphabet: MinMax): IntArray {170 val input = IntArray(size)171 fillRandom(rnd, input, size, alphabet)172 return input173 }174 /*175 * Fill an array with random symbols from the given alphabet/176 */177 fun fillRandom(rnd: Random, input: IntArray, size: Int, alphabet: MinMax) {178 for (j in input.indices) {179 input[j] = rnd.nextInt(alphabet.range() + 1) + alphabet.min180 }181 }182 }183}184private fun IntArray.clone(): IntArray =copyOf()185/**186 * Tests for [DivSufSort].187 */188class JvmDivSufSortTest : SuffixArrayBuilderTestBase() {189 private val alphabetSize = 256190 /*191 *192 */193 override val instance: ISuffixArrayBuilder194 get() = DivSufSort(alphabetSize)195 @BeforeTest196 fun setupForConstraints() {197 smallAlphabet=(MinMax(1, 10))198 largeAlphabet=(MinMax(1, alphabetSize - 1))199 }200}...
JsSampleTests.kt
Source:JsSampleTests.kt
1import org.jsuffixarrays.*2import kotlin.random.Random3import kotlin.test.*4/**5 * A set of shared tests and preconditions that all implementations of6 * [ISuffixArrayBuilder] should meet.7 */8abstract class JsSuffixArrayBuilderTestBase {9 lateinit var builder: ISuffixArrayBuilder10 var smallAlphabet: MinMax = MinMax(-5, 5)11 var largeAlphabet: MinMax = MinMax(-500, 500)12 /**13 * Subclasses must override and return a valid instance of [ISuffixArrayBuilder]14 * .15 */16 protected abstract val instance: ISuffixArrayBuilder17 @BeforeTest18 fun prepareBuilder() {19 builder = instance20 }21 /**22 * Check the suffixes of `banana`.23 */24 @Test25 fun checkBanana() {26 assertSuffixes("banana", "a", "ana", "anana", "banana", "na", "nana")27 }28 /**29 * Check the suffixes of `mississippi`.30 */31 @Test32 fun checkMississippi() {33 assertSuffixes("mississippi", "i", "ippi", "issippi", "ississippi",34 "mississippi", "pi", "ppi", "sippi", "sissippi", "ssippi", "ssissippi")35 }36 /**37 * Create a suffix array for the same input sequence, but placed at different offsets38 * in the input array. The result should be identical (not counting the offset of39 * course).40 *41 *42 * Checks the LCP array created for the given input as well.43 */44 @Test45 open fun sameResultWithArraySlice() {46 val builder = instance47 val sliceSize = 50048 val totalSize = 100049 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE50 val rnd = Random(0x11223344)51 val alphabet = MinMax(1, 50)52 val slice = generateRandom(rnd, sliceSize, alphabet)53 val total = generateRandom(rnd, totalSize + extraSpace, alphabet)54 var prevSuffixArray: IntArray? = null55 var prevLCP: IntArray? = null56 for (i in 0 until totalSize - slice.size) {57 val input = total.copyOf()58 arraycopy(slice, 0, input, i, slice.size)59 val clone = input.clone()60 val sa = builder.buildSuffixArray(input, i, slice.size)61 val lcp = SuffixArrays.computeLCP(input, i, slice.size, sa)62 assertEquals(clone.toList(), input.toList())63 if (prevSuffixArray != null) {64 assertEquals(prevSuffixArray.toList(), sa.toList())65 }66 prevSuffixArray = sa67 // Compare LCPs68 if (prevLCP != null) {69 assertEquals(prevLCP.toList(), lcp.toList())70 }71 prevLCP = lcp72 }73 }74 /**75 * Create suffix arrays for a few random sequences of integers, verify invariants76 * (every suffix array is a permutation of indices, every suffix in the suffix array77 * is lexicographically greater or equal than all its predecessors).78 */79 @Test80 fun invariantsOnRandomSmallAlphabet() {81 val builder = instance82 // Use constant seed so that we can repeat tests.83 val rnd = Random(0x11223344)84 val inputSize = 100085 val repeats = 50086 runRandom(builder, rnd, inputSize, repeats, smallAlphabet)87 }88 /**89 * @see .invariantsOnRandomSmallAlphabet90 */91 @Test92 open fun invariantsOnRandomLargeAlphabet() {93 val builder = instance94 // Use constant seed so that we can repeat tests.95 val rnd = Random(0x11223344)96 val inputSize = 100097 val repeats = 50098 runRandom(builder, rnd, inputSize, repeats, largeAlphabet)99 }100 /*101 * Run invariant checks on randomly generated data.102 */103 private fun runRandom(builder: ISuffixArrayBuilder, rnd: Random,104 inputSize: Int, repeats: Int, alphabet: MinMax) {105 val extraSpace = SuffixArrays.MAX_EXTRA_TRAILING_SPACE106 for (i in 0 until repeats) {107 val input = generateRandom(rnd, inputSize + extraSpace, alphabet)108 val copy = input.clone()109 val start = 0110 val SA = builder.buildSuffixArray(input, start, inputSize)111 assertEquals( input.toList(), copy.toList())112 assertPermutation(SA, inputSize)113 assertSorted(SA, input, inputSize)114 }115 }116 /*117 * Verify that two suffixes are less or equal.118 */119 private fun sleq(s1: IntArray, s1i: Int, s2: IntArray, s2i: Int, n: Int): Boolean {120 var s1i = s1i121 var s2i = s2i122 do {123 if (s1[s1i] < s2[s2i]) return true124 if (s1[s1i] > s2[s2i]) return false125 s2i++126 s1i++127 if (s1i == n) return true128 } while (true)129 }130 /*131 * Make sure suffixes in a suffix array are sorted.132 */133 private fun assertSorted(SA: IntArray, s: IntArray, n: Int) {134 for (i in 0 until n - 1) {135 if (!sleq(s, SA[i], s, SA[i + 1], n)) {136 fail("Suffix " + SA[i] + ">" + SA[i + 1] + ":\n" + SA[i] + ">"137 + s.slice(SA[i]until n) + "\n" + SA[i + 1]138 + ">" + s.slice (SA[i + 1].. n) + "\n" + "a>"139 + s.asList( ))140 }141 }142 }143 /*144 * Assert a suffix array is a permutation of indices.145 */146 private fun assertPermutation(SA: IntArray, length: Int) {147 val seen = BooleanArray(length)148 for (i in 0 until length) {149 assertFalse(seen[SA[i]])150 seen[SA[i]] = true151 }152 for (i in 0 until length) {153 assertTrue(seen[i])154 }155 }156 /*157 * Assert a suffix array built for a given input contains exactly the given set of158 * suffixes, in that order.159 */160 private fun assertSuffixes(input: CharSequence, vararg expectedSuffixes: CharSequence) {161 val suffixes = SuffixArrays.create(input, instance)162 assertEquals(expectedSuffixes.asList( ), SuffixArrays.toString(input,163 suffixes))164 }165 companion object {166 /*167 * Generate random data.168 */169 fun generateRandom(rnd: Random, size: Int, alphabet: MinMax): IntArray {170 val input = IntArray(size)171 fillRandom(rnd, input, size, alphabet)172 return input173 }174 /*175 * Fill an array with random symbols from the given alphabet/176 */177 fun fillRandom(rnd: Random, input: IntArray, size: Int, alphabet: MinMax) {178 for (j in input.indices) {179 input[j] = rnd.nextInt(alphabet.range() + 1) + alphabet.min180 }181 }182 }183}184private fun IntArray.clone(): IntArray =copyOf()185/**186 * Tests for [DivSufSort].187 */188class JsDivSufSortTest : SuffixArrayBuilderTestBase() {189 private val alphabetSize = 256190 /*191 *192 */193 override val instance: ISuffixArrayBuilder194 get() = DivSufSort(alphabetSize)195 @BeforeTest196 fun setupForConstraints() {197 smallAlphabet=(MinMax(1, 10))198 largeAlphabet=(MinMax(1, alphabetSize - 1))199 }200}...
Contest.kt
Source:Contest.kt
...151 (start until charArray.size).forEach {152 charArray[it] = ' '153 }154}155private fun InputStream.printIfNotTheSame(intArray: IntArray): IntArray {156 var readResult = read()157 if (readResult == -1) return intArray158 var index = 0159 var isTheSame = true160 while (readResult != -1 && readResult != CR) {161 if (intArray[index] != readResult) {162 isTheSame = false163 }164 intArray[index] = readResult165 readResult = read()166 index++167 }168 if (!isTheSame) {169 for (i in 0 until index) {170 print(intArray[i].toChar())171 }172 println()173 }174 return intArray175}176private fun InputStream.readInt(): Int {177 var readResult = read()178 if (readResult == -1) return -1179 var isNegative = false180 if (readResult == MINUS) {181 isNegative = true182 readResult = read()183 }184 var sum = 0185 while (readResult != -1 && readResult != CR) {186 sum = sum * 10 + readResult - ZERO187 readResult = read()188 }...
Solution.kt
Source:Solution.kt
1package year2021.day152import readInput3import kotlin.math.min4fun main() {5 val testInput = readInput(2021, 15, "test").parse()6 val input = readInput(2021, 15).parse()7 check(part1(testInput) == 40)8 println(part1(input))9 check(part2(testInput) == 315)10 println(part2(input))11}12private fun part1(grid: List<IntArray>): Int =13 grid.fillDijkstraMap().getValue(Point(grid.lastIndex, grid.first().lastIndex))14private fun part2(grid: List<IntArray>): Int =15 grid.multiply(5)16 .let { largeGrid ->17 largeGrid18 .aStar(Point(0, 0), Point(largeGrid.lastIndex, largeGrid.first().lastIndex))19 .drop(1).sumOf { largeGrid.get(it) }20 }21private fun List<IntArray>.fillDijkstraMap(): Map<Point, Int> {22 val result = mutableMapOf<Point, Int>()23 val visited = mutableSetOf<Point>()24 val unvisited = flatMapIndexed { i: Int, row: IntArray ->25 row.indices.map { j -> Point(i, j) }26 }.toMutableList()27 while (unvisited.isNotEmpty()) {28 val current = result.keys29 .filter { !visited.contains(it) }30 .minByOrNull { result.getValue(it) }31 ?: unvisited.first()32 val adjacentPoints = current.adjacentPoints().filter { point ->33 !visited.contains(point) && getOrNull(point.x)?.getOrNull(point.y) != null34 }35 adjacentPoints.forEach { point ->36 val possibleNewValue = result.getOrDefault(current, 0) + get(point)37 if (result.contains(point)) {38 val newValue = min(39 result.getValue(point),40 possibleNewValue41 )42 result[point] = newValue43 } else {44 result[point] = possibleNewValue45 }46 }47 visited.add(current)48 unvisited.remove(current)49 }50 return result51}52private fun List<IntArray>.aStar(start: Point, goal: Point): List<Point> {53 val h: (Point) -> Int = { current ->54 (goal.x - current.x) + (goal.y - current.y)55 }56 val openSet = mutableSetOf(start)57 val cameFrom = mutableMapOf<Point, Point>()58 val gScore = mutableMapOf<Point, Int>()59 gScore[start] = 060 val fScore = mutableMapOf<Point, Int>()61 fScore[start] = h(start)62 while (openSet.isNotEmpty()) {63 val current = openSet.minByOrNull { fScore.getValue(it) }!!64 if (current == goal) return reconstructPath(cameFrom, current)65 openSet.remove(current)66 val adjacentPoints = current.adjacentPoints().filter { point ->67 getOrNull(point.x)?.getOrNull(point.y) != null68 }69 adjacentPoints.forEach { neighbor ->70 val tentativeScore = gScore.getOrDefault(current, 0) + get(neighbor)71 if (tentativeScore < (gScore[neighbor] ?: Int.MAX_VALUE)) {72 cameFrom[neighbor] = current73 gScore[neighbor] = tentativeScore74 fScore[neighbor] = tentativeScore + h(neighbor)75 if (!openSet.contains(neighbor)) openSet.add(neighbor)76 }77 }78 }79 return emptyList()80}81private fun reconstructPath(cameFrom: Map<Point, Point>, end: Point): List<Point> {82 val path = mutableListOf<Point>()83 var current: Point? = end84 while (current != null) {85 path.add(0, current)86 current = cameFrom[current]87 }88 return path89}90private fun List<String>.parse(): List<IntArray> =91 map { line -> IntArray(line.length) { line[it].digitToInt() } }92private fun List<IntArray>.get(point: Point) = this[point.x][point.y]93private fun List<IntArray>.multiply(multiplier: Int): List<IntArray> =94 List(size * multiplier) { i ->95 val originalRowIndex = i.mod(size)96 val chunkRowIndex = i / size97 val rowSize = get(originalRowIndex).size98 IntArray(rowSize * multiplier) { j ->99 val originalColumnIndex = j.mod(rowSize)100 val chunkColumnIndex = j / rowSize101 val originalValue = this[originalRowIndex][originalColumnIndex]102 val rawValue = originalValue + chunkColumnIndex + chunkRowIndex103 if (rawValue / 10 < 1) {104 rawValue105 } else {106 rawValue.mod(10) + 1107 }108 }109 }110private data class Point(val x: Int, val y: Int) {111 fun adjacentPoints(): Set<Point> = buildSet {112 add(Point(x, y - 1))113 add(Point(x, y + 1))114 add(Point(x - 1, y))115 add(Point(x + 1, y))116 }117}...
Day4.kt
Source:Day4.kt
1package day42import java.io.File3open class Day4 {4// open val input = File("src/main/kotlin/day4/test-input.txt").readLines()5// open val input = File("src/main/kotlin/day4/test-input-hor-column-win.txt").readLines()6 open val input = File("src/main/kotlin/day4/input.txt").readLines()7 open fun createDrawNumbers(input: List<String>, drawNumbers: (List<Int>) -> Unit) =8 drawNumbers(input.first().split(',').map(String::toInt))9 open fun createBoards(input: List<String>, createdBoards: (List<Array<IntArray>>) -> Unit) {10 val boards = mutableListOf<Array<IntArray>>()11 input.forEachIndexed { rowIndex, rowString ->12 if (rowString.isBlank()) {13 val boardAsStrings = input.subList(rowIndex + 1, rowIndex + 6)14 boards.add(createBoard(boardAsStrings))15 }16 }17 createdBoards(boards)18 }19 private fun createBoard(boardAsStrings: List<String>): Array<IntArray> {20 val boardArray: Array<IntArray> = arrayOf(IntArray(5), IntArray(5), IntArray(5), IntArray(5), IntArray(5))21 boardAsStrings.forEachIndexed { rowIndex, rowString ->22 val formattedRowString = formatRowString(rowString)23 boardArray[rowIndex] = formattedRowString.split(',').map(String::toInt).toIntArray()24 }25 return boardArray26 }27 /** Replace all space and double spaces with comma (,)*/28 private fun formatRowString(rowString: String): String {29 val formattedRowString: String =30 if (rowString[0] == ' ') rowString.substring(1, rowString.length) else rowString31 return formattedRowString.replace(" ", ",").replace(' ', ',')32 }33 open fun calculateScore(winningBoard: Array<IntArray>, lastNumber: Int): Int {34 var sumOfUnmarkedNumbers = 035 winningBoard.forEach { row ->36 row.forEach { number ->37 if (number != MARKED_NUMBER) sumOfUnmarkedNumbers += number38 }39 }40 return sumOfUnmarkedNumbers * lastNumber41 }42 companion object {43 const val MARKED_NUMBER = -144 var nextTimeToCheckForFiveInARow = 445 }46}...
intArray
Using AI Code Generation
1 int[] intArray = new int[5];2 for (int i = 0; i < intArray.length; i++) {3 intArray[i] = i * 10;4 }5 test.Open intArrayMethod = new test.Open();6 intArrayMethod.intArray(intArray);7 }8}9package test;10public class Open {11 public void intArray(int[] intArray) {12 for (int i = 0; i < intArray.length; i++) {13 System.out.println("Element " + i + ", value is " + intArray[i]);14 }15 }16}17final void run(){System.out.println("running");}18class Honda extends Bike{ 19 void run(){System.out.println("running safely with 100kmph");} 20 public static void main(String args[]){ 21 Honda honda= new Honda(); 22 honda.run(); 23 } 24}25final class Bike{}26class Honda1 extends Bike{ 27 void run(){System.out.println("running safely with 100kmph");} 28 public static void main(String args[]){ 29 Honda1 honda= new Honda1(); 30 honda.run(); 31 } 32}33class Animal{
intArray
Using AI Code Generation
1 test.Open intArray = new test.Open();2 intArray.intArray();3 }4}5package test;6public class Open {7 public void intArray(){8 int[] arr = new int[3];9 arr[0] = 1;10 arr[1] = 2;11 arr[2] = 3;12 for(int i = 0; i < arr.length; i++){13 System.out.println(arr[i]);14 }15 }16}17public int[] getNumbers(String s){18}19public class Test{20 public static void main(String[] args){21 String[] s = getStrings();22 for(int i = 0; i < s.length; i++){23 System.out.println(s[i]);24 }25 }26 public String[] getStrings(){27 String[] s = new String[3];28 s[0] = "Hello";29 s[1] = "World";30 s[2] = "!";31 return s;32 }33}34public int[] getNumbers(String s){35}36public int[] getNumbers(String s){37}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!