content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
package lc_283
class Solution {
fun moveZeroes(nums: IntArray) {
var zeroCount = 0
nums.forEachIndexed { i, num -> if (num == 0) ++zeroCount else nums[i - zeroCount] = num }
repeat(zeroCount) { nums[nums.lastIndex - it] = 0 }
}
}
| LC-PS/src/lc_283/Solution.kt | 112210628 |
package lc_841
import java.util.LinkedList
class Solution {
fun canVisitAllRooms(rooms: List<List<Int>>): Boolean {
val isVisited = BooleanArray(rooms.size).apply { this[0] = true }
val nextNums = LinkedList<Int>().apply { offer(0) }
while (nextNums.isNotEmpty()) {
rooms[nextNums.poll()].forEach { num ->
if (isVisited[num]) return@forEach
isVisited[num] = true
nextNums.offer(num)
}
}
return isVisited.all { it }
}
}
| LC-PS/src/lc_841/Solution.kt | 2009016192 |
package lc_1492
class Solution {
fun kthFactor(n: Int, k: Int): Int {
var j = 0
for (i in 1..n) if (n % i == 0 && ++j == k) return i
return -1
}
}
| LC-PS/src/lc_1492/Solution.kt | 1880409768 |
package lc_88
class Solution {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
val tmp = IntArray(nums1.size)
var left = 0
var right = 0
for (i in nums1.indices) {
tmp[i] = when {
left == m -> nums2[right++]
right == n -> nums1[left++]
nums1[left] <= nums2[right] -> nums1[left++]
else -> nums2[right++]
}
}
for (i in nums1.indices) nums1[i] = tmp[i]
}
}
| LC-PS/src/lc_88/Solution.kt | 3923601006 |
package lc_290
import java.util.StringTokenizer
class Solution {
fun wordPattern(pattern: String, s: String): Boolean {
val st = StringTokenizer(s)
val isUsed = BooleanArray(size = 26)
val patternCharOf = hashMapOf<String, Char>()
var i = 0
while (st.hasMoreTokens()) {
val word = st.nextToken()
val patternChar = patternCharOf[word]
if (patternChar == null) {
val j = pattern[i] - 'a'
if (isUsed[j]) return false
patternCharOf[word] = pattern[i]
isUsed[j] = true
} else if (pattern.lastIndex < i || patternChar != pattern[i]) {
return false
}
++i
}
return i == pattern.length
}
}
| LC-PS/src/lc_290/Solution.kt | 159076854 |
package lc_1475
import java.util.Stack
class Solution {
fun finalPrices(prices: IntArray): IntArray {
val answer = prices.clone()
val stack = Stack<Pair<Int, Int>>()
prices.forEachIndexed { i, price ->
while (stack.isNotEmpty() && price <= stack.peek().second) {
val (j, prevPrice) = stack.pop()
answer[j] = prevPrice - price
}
stack.push(i to price)
}
return answer
}
}
| LC-PS/src/lc_1475/Solution.kt | 342114518 |
package lc_206
class Solution {
fun reverseList(head: ListNode?): ListNode? {
var current = head
var prev: ListNode? = null
while (current != null) {
val next = current.next
current.next = prev
prev = current
current = next
}
return prev
}
}
class ListNode {
var next: ListNode? = null
}
| LC-PS/src/lc_206/Solution.kt | 2438531984 |
package lc_35
class Solution {
fun searchInsert(nums: IntArray, target: Int): Int {
var low = 0
var high = nums.size
while (low < high) {
val mid = low + high shr 1
if (nums[mid] < target) low = mid + 1 else high = mid
}
return high
}
}
| LC-PS/src/lc_35/Solution.kt | 1835263362 |
package lc_208
class Trie {
private var c: Char = ' '
private var children: Array<Trie?> = Array(size = 26) { null }
private var isTerminal: Boolean = false
fun insert(word: String) {
var node = this
word.forEach { c ->
val i = c - 'a'
if (node.children[i] == null) node.children[i] = Trie().apply { this.c = c }
node = requireNotNull(node.children[i])
}
node.isTerminal = true
}
fun search(word: String): Boolean {
var node = this
word.forEach { c ->
val i = c - 'a'
if (node.children[i] == null) return false
node = requireNotNull(node.children[i])
}
return node.isTerminal
}
fun startsWith(prefix: String): Boolean {
var node = this
prefix.forEach { c ->
val i = c - 'a'
if (node.children[i] == null) return false
node = requireNotNull(node.children[i])
}
return true
}
}
| LC-PS/src/lc_208/Solution.kt | 2083503517 |
package lc_1679
class Solution {
fun maxOperations(nums: IntArray, k: Int): Int {
nums.sort()
var left = 0
var right = nums.lastIndex
var count = 0
while (left < right) {
val sum = nums[left] + nums[right]
when {
sum < k -> ++left
k < sum -> --right
else -> {
++count
++left
--right
}
}
}
return count
}
}
| LC-PS/src/lc_1679/Solution.kt | 501270229 |
package lc_58
class Solution {
fun lengthOfLastWord(s: String): Int {
var len = 0
for (i in s.indices.reversed()) if (s[i] != ' ') ++len else if (0 < len) break
return len
}
}
| LC-PS/src/lc_58/Solution.kt | 2228922015 |
package lc_236
class Solution {
private val parentOf: HashMap<TreeNode, TreeNode> = hashMapOf()
private val isVisited: HashSet<TreeNode> = hashSetOf()
private var lcaNode: TreeNode? = null
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
findParents(root)
markVisitedNodes(p)
findLcaNode(q)
return lcaNode
}
private fun findParents(node: TreeNode?) {
node?.left?.let {
parentOf[it] = node
findParents(it)
}
node?.right?.let {
parentOf[it] = node
findParents(it)
}
}
private fun markVisitedNodes(node: TreeNode?) {
node ?: return
isVisited.add(node)
markVisitedNodes(parentOf[node])
}
private fun findLcaNode(node: TreeNode?) {
node ?: return
if (node in isVisited) {
lcaNode = node
return
}
findLcaNode(parentOf[node])
}
}
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_236/Solution.kt | 1704656699 |
package lc_238
class Solution {
fun productExceptSelf(nums: IntArray): IntArray {
val results = IntArray(nums.size) { 1 }
val lastIdx = nums.lastIndex
var forwardMultiple = 1
var backwardMultiple = 1
for (i in nums.indices) {
results[i] *= forwardMultiple
results[lastIdx - i] *= backwardMultiple
forwardMultiple *= nums[i]
backwardMultiple *= nums[lastIdx - i]
}
return results
}
}
| LC-PS/src/lc_238/Solution.kt | 789506292 |
package lc_122
class Solution {
fun maxProfit(prices: IntArray): Int {
var sellPrice = -1
var profit = 0
for (i in prices.indices.reversed()) {
if (prices[i] < sellPrice) profit += sellPrice - prices[i]
sellPrice = prices[i]
}
return profit
}
}
| LC-PS/src/lc_122/Solution.kt | 128485251 |
package lc_125
class Solution {
fun isPalindrome(s: String): Boolean {
val alphanumeric = buildString {
s.forEach {
when (it) {
in 'a'..'z', in '0'..'9' -> append(it)
in 'A'..'Z' -> append(it + ('a' - 'A'))
else -> return@forEach
}
}
}
var left = 0
var right = alphanumeric.lastIndex
while (left < right) {
if (alphanumeric[left++] != alphanumeric[right--]) return false
}
return true
}
}
| LC-PS/src/lc_125/Solution.kt | 3362856763 |
package lc_328
class Solution {
fun oddEvenList(head: ListNode?): ListNode? {
head ?: return null
val oddEven = ListNode(head.`val`)
var oddEvenNext: ListNode? = oddEven
var next = head.next?.next
while (next != null) {
oddEvenNext?.next = ListNode(next.`val`)
oddEvenNext = oddEvenNext?.next
next = next.next?.next
}
next = head.next
while (next != null) {
oddEvenNext?.next = ListNode(next.`val`)
oddEvenNext = oddEvenNext?.next
next = next.next?.next
}
return oddEven
}
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
| LC-PS/src/lc_328/Solution.kt | 2475401899 |
package lc_1768
class Solution {
fun mergeAlternately(word1: String, word2: String): String = buildString {
var i = 0
var j = 0
val mergedLength = word1.length + word2.length
while (i + j <= mergedLength - 1) {
if (i < word1.length) append(word1[i++])
if (j < word2.length) append(word2[j++])
}
}
}
| LC-PS/src/lc_1768/Solution.kt | 2191266827 |
package lc_345
class Solution {
fun reverseVowels(s: String): String {
val vowels = setOf('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U')
var i = 0
var j = s.lastIndex
val chars = CharArray(s.length)
mainLoop@ while (i <= j) {
while (i <= s.lastIndex && s[i] !in vowels) {
if (j < i) break@mainLoop
chars[i] = s[i++]
}
while (0 <= j && s[j] !in vowels) {
if (j < i) break@mainLoop
chars[j] = s[j--]
}
chars[i] = s[j]
chars[j--] = s[i++]
}
return String(chars)
}
}
fun main() {
print(Solution().reverseVowels("ai"))
}
| LC-PS/src/lc_345/Solution.kt | 4131829753 |
package lc_141
class Solution {
fun hasCycle(head: ListNode?): Boolean {
var fast = head
var slow = head
while (fast?.next != null) {
fast = fast.next?.next
slow = slow?.next
if (fast == slow) return true
}
return false
}
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
| LC-PS/src/lc_141/Solution.kt | 18375152 |
package lc_1137
class Solution {
fun tribonacci(n: Int): Int {
if (n < 1) return 0
if (n < 3) return 1
var first = 0
var second = 1
var third = 1
repeat(times = n - 2) {
val tmp1 = third
third += first + second
val tmp2 = second
second = tmp1
first = tmp2
}
return third
}
}
| LC-PS/src/lc_1137/Solution.kt | 3733139685 |
package lc_1732
class Solution {
fun largestAltitude(gain: IntArray): Int {
var highest = 0
gain.fold(initial = 0) { acc, diff ->
(acc + diff).also { if (highest < it) highest = it }
}
return highest
}
}
| LC-PS/src/lc_1732/Solution.kt | 2218619353 |
package lc_112
class Solution {
fun hasPathSum(root: TreeNode?, targetSum: Int): Boolean {
root ?: return false
if (root.left == null && root.right == null) return targetSum == root.`val`
val nextTargetSum = targetSum - root.`val`
return hasPathSum(root.left, nextTargetSum) || hasPathSum(root.right, nextTargetSum)
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_112/Solution.kt | 357100257 |
package lc_547
import java.util.LinkedList
class Solution {
fun findCircleNum(isConnected: Array<IntArray>): Int {
val isVisited = BooleanArray(isConnected.size)
val nextCities = LinkedList<Int>()
var size = 0
for (i in isConnected.indices) {
if (isVisited[i]) continue
isVisited[i] = true
nextCities.offer(i)
++size
while (nextCities.isNotEmpty()) {
isConnected[nextCities.poll()].forEachIndexed { j, c ->
if (c == 0 || isVisited[j]) return@forEachIndexed
isVisited[j] = true
nextCities.offer(j)
}
}
}
return size
}
}
| LC-PS/src/lc_547/Solution.kt | 540393553 |
package lc_503
import java.util.Stack
class Solution {
fun nextGreaterElements(nums: IntArray): IntArray {
val answer = IntArray(nums.size) { -1 }
val stack = Stack<Pair<Int, Int>>()
repeat(times = 2) {
nums.forEachIndexed { i, num ->
while (stack.isNotEmpty() && stack.peek().second < num) {
answer[stack.pop().first] = num
}
stack.push(i to num)
}
}
return answer
}
}
| LC-PS/src/lc_503/Solution.kt | 2640919220 |
package lc_167
class Solution {
fun twoSum(numbers: IntArray, target: Int): IntArray {
var left = 0
var right = numbers.lastIndex
while (true) {
val sum = numbers[left] + numbers[right]
when {
sum < target -> ++left
target < sum -> --right
else -> break
}
}
return intArrayOf(left + 1, right + 1)
}
}
| LC-PS/src/lc_167/Solution.kt | 3533509673 |
package lc_700
class Solution {
fun searchBST(root: TreeNode?, `val`: Int): TreeNode? = when {
root == null -> null
`val` < root.`val` -> searchBST(root.left, `val`)
root.`val` < `val` -> searchBST(root.right, `val`)
else -> root
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_700/Solution.kt | 3899487241 |
package lc_169
class Solution {
fun majorityElement(nums: IntArray): Int {
var size = 0
var element = Int.MIN_VALUE
nums.forEach {
if (size == 0) {
element = it
++size
return@forEach
}
if (element == it) ++size else --size
}
return element
}
}
| LC-PS/src/lc_169/Solution.kt | 1175406820 |
package lc_151
class Solution {
fun reverseWords(s: String): String {
val words = s.trim().split("\\s+".toRegex()).toMutableList()
var i = 0
var j = words.lastIndex
while (i < j) {
val tmp = words[i]
words[i++] = words[j]
words[j--] = tmp
}
return words.joinToString(separator = " ")
}
}
| LC-PS/src/lc_151/Solution.kt | 599105656 |
package lc_739
import java.util.Stack
class Solution {
fun dailyTemperatures(temperatures: IntArray): IntArray {
val answer = IntArray(temperatures.size)
val stack = Stack<Int>()
for (i in temperatures.indices) {
while (stack.isNotEmpty() && temperatures[stack.peek()] < temperatures[i]) {
val j = stack.pop()
answer[j] = i - j
}
stack.push(i)
}
return answer
}
}
| LC-PS/src/lc_739/Solution.kt | 695763535 |
package lc_2130
class Solution {
fun pairSum(head: ListNode?): Int {
var next = head
var tail = head
do {
next = next?.next
next?.`val`?.let {
val newTail = ListNode(it)
newTail.next = tail
tail = newTail
}
} while (next != null)
var left = head
var right = tail
var maxSum = 0
while (left != null && right != null) {
val sum = left.`val` + right.`val`
if (maxSum < sum) maxSum = sum
left = left.next
right = right.next
}
return maxSum
}
}
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
| LC-PS/src/lc_2130/Solution.kt | 2317799251 |
package lc_338
class Solution {
fun countBits(n: Int): IntArray {
val arr = IntArray(size = n + 1)
for (i in arr.indices) {
val half = i shr 1
arr[i] = arr[half]
if (half shl 1 < i) ++arr[i]
}
return arr
}
}
| LC-PS/src/lc_338/Solution.kt | 4160514897 |
package lc_135
class Solution {
fun candy(ratings: IntArray): Int {
val numberOf = IntArray(ratings.size) { 1 }
for (i in 1 until ratings.size) {
if (ratings[i - 1] < ratings[i]) {
numberOf[i] = numberOf[i - 1] + 1
}
}
for (i in ratings.lastIndex - 1 downTo 0) {
if (ratings[i + 1] < ratings[i]) {
numberOf[i] = maxOf(numberOf[i], b = numberOf[i + 1] + 1)
}
}
return numberOf.sum()
}
}
| LC-PS/src/lc_135/Solution.kt | 546647471 |
package lc_104
import kotlin.math.max
class Solution {
fun maxDepth(root: TreeNode?): Int =
root?.let { max(a = maxDepth(it.left) + 1, b = maxDepth(it.right) + 1) } ?: 0
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_104/Solution.kt | 2053441894 |
package lc_2215
class Solution {
fun findDifference(nums1: IntArray, nums2: IntArray): List<List<Int>> {
val set1 = nums1.toSet()
val set2 = nums2.toSet()
return listOf(set1.filter { it !in set2 }, set2.filter { it !in set1 })
}
}
| LC-PS/src/lc_2215/Solution.kt | 2424795951 |
package lc_875
class Solution {
fun minEatingSpeed(piles: IntArray, h: Int): Int {
var min = 1
var max = piles.max()
while (min <= max) {
val mid = min + max shr 1
val sum = piles.sumOf { it.toLong() / mid + if (it % mid == 0) 0L else 1L }
if (sum <= h) max = mid - 1 else min = mid + 1
}
return min
}
}
| LC-PS/src/lc_875/Solution.kt | 1198354025 |
package lc_872
import java.util.LinkedList
class Solution {
fun leafSimilar(root1: TreeNode?, root2: TreeNode?): Boolean {
val leaf1 = LinkedList<Int>()
dfs(root1, leaf1)
val leaf2 = LinkedList<Int>()
dfs(root2, leaf2)
return leaf1 == leaf2
}
private fun dfs(node: TreeNode?, leafs: LinkedList<Int>) {
node ?: return
if (node.left == null && node.right == null) leafs.add(node.`val`)
dfs(node.left, leafs)
dfs(node.right, leafs)
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_872/Solution.kt | 47301033 |
package lc_70
class Solution {
fun climbStairs(n: Int): Int {
var one = 0
var two = 1
for (i in 2..n + 1) {
val tmp = two
two += one
one = tmp
}
return two
}
}
| LC-PS/src/lc_70/Solution.kt | 1226706309 |
package lc_219
class Solution {
fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean {
buildMap<Int, Int> {
nums.forEachIndexed { i, num ->
this[num]?.let { if (i - it <= k) return true }
this[num] = i
}
}
return false
}
}
| LC-PS/src/lc_219/Solution.kt | 3570637296 |
package lc_226
class Solution {
fun invertTree(root: TreeNode?): TreeNode? {
root ?: return null
val tmp = root.left
root.left = root.right
root.right = tmp
invertTree(root.left)
invertTree(root.right)
return root
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_226/Solution.kt | 2916638925 |
package lc_1268
import java.util.TreeMap
class Solution {
fun suggestedProducts(products: Array<String>, searchWord: String): List<List<String>> {
val root = Node()
products.forEach(root::add)
val suggests = mutableListOf<List<String>>()
val keywordBuilder = StringBuilder()
searchWord.forEach { c ->
keywordBuilder.append(c)
suggests.add(root.suggest(keywordBuilder.toString()))
}
return suggests
}
private data class Node(val c: Char = ' ') {
private val children: TreeMap<Char, Node> = TreeMap()
private var isTerminal: Boolean = false
fun add(keyword: String) {
var node = this
keyword.forEach { c ->
if (node.children[c] == null) node.children[c] = Node(c)
node = requireNotNull(node.children[c])
}
node.isTerminal = true
}
fun suggest(keyword: String): List<String> {
val suggests = mutableListOf<String>()
var node = this
keyword.forEach { c ->
if (node.children[c] == null) return emptyList()
node = requireNotNull(node.children[c])
}
fun dfs(node: Node, sb: StringBuilder = StringBuilder(keyword)) {
if (3 <= suggests.size) return
if (node.isTerminal) suggests.add(sb.toString())
node.children.values.forEach { child ->
dfs(child, StringBuilder(sb).append(child.c))
}
}
dfs(node)
return suggests
}
}
}
| LC-PS/src/lc_1268/Solution.kt | 3514698972 |
package lc_228
class Solution {
fun summaryRanges(nums: IntArray): List<String> {
if (nums.isEmpty()) return emptyList()
val ranges = mutableListOf<String>()
var start = 0
for (end in 1 until nums.size) {
val previous = end - 1
if (nums[previous] + 1 < nums[end]) {
val range = if (start == previous) {
nums[previous].toString()
} else {
"${nums[start]}->${nums[previous]}"
}
ranges.add(range)
start = end
}
}
val last = nums.lastIndex
val range = if (start == last) {
nums[last].toString()
} else {
"${nums[start]}->${nums[last]}"
}
ranges.add(range)
return ranges
}
}
| LC-PS/src/lc_228/Solution.kt | 3514744101 |
package lc_12
class Solution {
fun intToRoman(num: Int): String {
val valueOf =
intArrayOf(1_000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
val symbolOf =
arrayOf("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")
var remainder = num
val sb = StringBuilder()
valueOf.forEachIndexed { i, value ->
while (value <= remainder) {
remainder -= value
sb.append(symbolOf[i])
}
}
return sb.toString()
}
}
| LC-PS/src/lc_12/Solution.kt | 2514704956 |
package lc_49
class Solution {
fun groupAnagrams(strs: Array<String>): List<List<String>> =
strs.groupBy { String(it.toCharArray().apply { sort() }) }.values.toList()
}
| LC-PS/src/lc_49/Solution.kt | 204414165 |
package lc_242
class Solution {
fun isAnagram(s: String, t: String): Boolean {
if (s.length != t.length) return false
val frequencyOf = IntArray(size = 26)
s.forEachIndexed { i, c ->
++frequencyOf[c - 'a']
--frequencyOf[t[i] - 'a']
}
return frequencyOf.all { it == 0 }
}
}
| LC-PS/src/lc_242/Solution.kt | 3134417316 |
package lc_1657
class Solution {
fun closeStrings(word1: String, word2: String): Boolean {
if (word1.length != word2.length) return false
val word1CharToCount = word1.groupBy { it }.mapValues { it.value.size }
val word2CharToCount = word2.groupBy { it }.mapValues { it.value.size }
if (word1CharToCount.keys != word2CharToCount.keys) return false
val word1CountToCount = word1CharToCount.values.groupBy { it }.mapValues { it.value.size }
val word2CountToCount = word2CharToCount.values.groupBy { it }.mapValues { it.value.size }
return word1CountToCount == word2CountToCount
}
}
| LC-PS/src/lc_1657/Solution.kt | 3498622871 |
package lc_13
class Solution {
fun romanToInt(s: String): Int {
var sum = 0
for (i in s.lastIndex downTo 0) {
val j = i + 1
sum += when (s[i]) {
'I' -> if (j < s.length && (s[j] == 'V' || s[j] == 'X')) -1 else 1
'V' -> 5
'X' -> if (j < s.length && (s[j] == 'L' || s[j] == 'C')) -10 else 10
'L' -> 50
'C' -> if (j < s.length && (s[j] == 'D' || s[j] == 'M')) -100 else 100
'D' -> 500
else -> 1_000
}
}
return sum
}
}
| LC-PS/src/lc_13/Solution.kt | 1848042575 |
package lc_1431
class Solution {
fun kidsWithCandies(candies: IntArray, extraCandies: Int): List<Boolean> {
val maxCandies = candies.max()
return candies.map { maxCandies <= it + extraCandies }
}
}
| LC-PS/src/lc_1431/Solution.kt | 842472640 |
package lc_14
class Solution {
fun longestCommonPrefix(strs: Array<String>): String {
if (strs.isEmpty()) return ""
val root = Node()
for (str in strs) {
if (str.isEmpty()) return ""
var node = root
for (c in str) {
if (node.children[c] == null) {
node.children[c] = Node(c)
if (node == root && 1 < node.children.size) return ""
}
node = requireNotNull(node.children[c])
}
node.isTerminal = true
}
if (root.children.isEmpty()) return ""
var node = root
val prefixBuilder = StringBuilder()
while (!node.isTerminal && node.children.size == 1) {
node = node.children.values.first()
prefixBuilder.append(node.c)
}
return prefixBuilder.toString()
}
private data class Node(val c: Char = ' ') {
val children: HashMap<Char, Node> = hashMapOf()
var isTerminal: Boolean = false
}
}
| LC-PS/src/lc_14/Solution.kt | 3191867941 |
package lc_643
class Solution {
fun findMaxAverage(nums: IntArray, k: Int): Double {
var subSum = 0
repeat(k) { subSum += nums[it] }
var maxSubSum = subSum
for (i in k..<nums.size) {
subSum += nums[i] - nums[i - k]
if (maxSubSum < subSum) maxSubSum = subSum
}
return maxSubSum.toDouble() / k
}
}
| LC-PS/src/lc_643/Solution.kt | 1714772966 |
package lc_205
class Solution {
fun isIsomorphic(s: String, t: String): Boolean {
val tOf = hashMapOf<Char, Char>()
val sOf = hashMapOf<Char, Char>()
s.forEachIndexed { i, sc ->
val tc = t[i]
if (sc !in tOf && tc !in sOf) {
tOf[sc] = tc
sOf[tc] = sc
} else if (tOf[sc] != tc || sOf[tc] != sc) {
return false
}
}
return true
}
}
| LC-PS/src/lc_205/Solution.kt | 437357395 |
package lc_2095
class Solution {
fun deleteMiddle(head: ListNode?): ListNode? {
head?.next ?: return null
var prev: ListNode? = null
var slow = head
var fast = head
while (fast?.next != null) {
prev = slow
slow = slow?.next
fast = fast.next?.next
}
prev?.next = slow?.next
return head
}
}
class ListNode {
var next: ListNode? = null
}
| LC-PS/src/lc_2095/Solution.kt | 608399035 |
package lc_202
class Solution {
fun isHappy(n: Int): Boolean {
val isVisited = mutableSetOf<String>()
var str = n.toString()
while (str !in isVisited) {
isVisited.add(str)
val digitSquareSum = str.sumOf {
val digit = it - '0'
(digit * digit).toLong()
}
if (digitSquareSum == 1L) return true
str = digitSquareSum.toString()
}
return false
}
}
| LC-PS/src/lc_202/Solution.kt | 237574066 |
package lc_2405
class Solution {
fun partitionString(s: String): Int {
var isVisited = BooleanArray(size = 26)
var size = 1
s.forEach { c ->
val i = c - 'a'
if (isVisited[i]) {
++size
isVisited = BooleanArray(size = 26).apply { this[i] = true }
return@forEach
}
isVisited[i] = true
}
return size
}
}
| LC-PS/src/lc_2405/Solution.kt | 1723260891 |
package lc_496
import java.util.Stack
class Solution {
fun nextGreaterElement(nums1: IntArray, nums2: IntArray): IntArray {
val num2Idx = HashMap<Int, Int>()
nums2.forEachIndexed { i, num -> num2Idx[num] = i }
val stack = Stack<Int>()
val nge = IntArray(nums2.size) { -1 }
for (i in nums2.lastIndex downTo 0) {
while (stack.isNotEmpty() && stack.peek() < nums2[i]) stack.pop()
if (stack.isNotEmpty()) nge[i] = stack.peek()
stack.push(nums2[i])
}
val result = IntArray(nums1.size)
for (i in nums1.indices) result[i] = nge[num2Idx[nums1[i]]!!]
return result
}
}
| LC-PS/src/lc_496/Solution.kt | 2008227746 |
package lc_53
class Solution {
fun maxSubArray(nums: IntArray): Int {
var maxSum = Int.MIN_VALUE
var previous = 0
nums.forEach {
previous = maxOf(a = previous + it, it)
maxSum = maxOf(maxSum, previous)
}
return maxSum
}
}
| LC-PS/src/lc_53/Solution.kt | 2951548496 |
package lc_1071
class Solution {
fun gcdOfStrings(str1: String, str2: String): String =
str1.substring(startIndex = 0, endIndex = gcd(str1.length, str2.length))
.takeIf { str1 + str2 == str2 + str1 }
.orEmpty()
private fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, b = a % b)
}
| LC-PS/src/lc_1071/Solution.kt | 1501888121 |
package lc_1448
class Solution {
private var count: Int = 0
fun goodNodes(root: TreeNode?): Int {
root?.let { dfs(it, it.`val`) }
return count
}
private fun dfs(root: TreeNode?, max: Int) {
root ?: return
var newMax = max
if (max <= root.`val`) {
newMax = root.`val`
++count
}
dfs(root.left, newMax)
dfs(root.right, newMax)
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
| LC-PS/src/lc_1448/Solution.kt | 3273517421 |
package lc_55
class Solution {
fun canJump(nums: IntArray): Boolean {
if (nums.size == 1) return true
var i = nums.lastIndex
var j = -1
while (-1 < i) {
if (nums[i] == 0 && j == -1) {
j = i
} else {
val maxJumpedIndex = i + nums[i]
if (j < maxJumpedIndex || (j == nums.lastIndex && j == maxJumpedIndex)) j = -1
}
--i
}
return j == -1
}
}
| LC-PS/src/lc_55/Solution.kt | 4110323006 |
package lc_437
class Solution {
private val isStarted: HashSet<TreeNode?> = hashSetOf()
private var count: Int = 0
fun pathSum(root: TreeNode?, targetSum: Int): Int {
isStarted.add(root)
dfs(root, targetSum.toLong())
return count
}
private fun dfs(node: TreeNode?, targetSum: Long, sum: Long = 0L) {
node ?: return
if (sum + node.`val` == targetSum) ++count
if (node.left !in isStarted) {
isStarted.add(node.left)
dfs(node.left, targetSum, sum = 0)
}
dfs(node.left, targetSum, sum = sum + node.`val`)
if (node.right !in isStarted) {
isStarted.add(node.right)
dfs(node.right, targetSum, sum = 0)
}
dfs(node.right, targetSum, sum = sum + node.`val`)
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun main() {
val root = TreeNode(1).apply {
right = TreeNode(2).apply {
right = TreeNode(3).apply {
right = TreeNode(4).apply {
right = TreeNode(5)
}
}
}
}
println(Solution().pathSum(root, targetSum = 3))
}
| LC-PS/src/lc_437/Solution.kt | 598835769 |
package lc_605
class Solution {
fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
if (n < 1) return true
var plantedCount = 0
for (i in flowerbed.indices) {
if (flowerbed.isUnableToPlant(i)) continue
flowerbed[i] = 1
if (n <= ++plantedCount) return true
}
return false
}
private fun IntArray.isUnableToPlant(i: Int): Boolean {
val checkStart = (i - 1).coerceAtLeast(minimumValue = 0)
val checkEnd = (i + 1).coerceAtMost(lastIndex)
val checkRange = checkStart..checkEnd
return checkRange.any { this[it] == 1 }
}
}
| LC-PS/src/lc_605/Solution.kt | 2697106004 |
package lc_121
class Solution {
fun maxProfit(prices: IntArray): Int {
var maxPrice = prices.last()
var maxProfit = Int.MIN_VALUE
for (i in prices.lastIndex - 1 downTo 0) {
val buyPrice = prices[i]
maxProfit = maxOf(maxProfit, b = maxPrice - buyPrice)
maxPrice = maxOf(maxPrice, buyPrice)
}
return maxProfit.coerceAtLeast(minimumValue = 0)
}
}
| LC-PS/src/lc_121/Solution.kt | 2029060272 |
package lc_1161
import java.util.LinkedList
class Solution {
fun maxLevelSum(root: TreeNode?): Int {
val nodes = LinkedList<Pair<TreeNode?, Int>>().apply { offer(root to 1) }
val sumOf = hashMapOf<Int, Int>()
while (nodes.isNotEmpty()) {
val (node, lev) = nodes.poll()
if (node == null) continue
sumOf[lev] = sumOf.getOrDefault(lev, defaultValue = 0) + node.`val`
val nextLevel = lev + 1
nodes.offer(node.left to nextLevel)
nodes.offer(node.right to nextLevel)
}
return sumOf.entries.maxByOrNull { it.value }?.key ?: 0
}
}
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun main() {
val root = TreeNode(1).apply {
left = TreeNode(7).apply {
left = TreeNode(7)
right = TreeNode(-8)
}
right = TreeNode(0)
}
println(Solution().maxLevelSum(root))
}
| LC-PS/src/lc_1161/Solution.kt | 2253193490 |
package lc_322
class Solution {
fun coinChange(coins: IntArray, amount: Int): Int {
coins.sort()
val inf = Int.MAX_VALUE shr 1
val countOf = IntArray(size = amount + 1) { inf }.apply { this[0] = 0 }
for (i in 1..amount) {
for (j in coins.indices) {
val coin = coins[j]
if (amount < coin) break
var remainder = i
var count = 0
while (coin <= remainder) {
remainder -= coin
countOf[i] = minOf(countOf[i], b = countOf[remainder] + ++count)
}
}
}
return if (countOf[amount] == Int.MAX_VALUE) -1 else countOf[amount]
}
}
| LC-PS/src/lc_322/Solution.kt | 2222655045 |
package lc_746
class Solution {
fun minCostClimbingStairs(cost: IntArray): Int {
for (i in 2 until cost.size) {
cost[i] += minOf(cost[i - 2], cost[i - 1])
}
return minOf(cost[cost.lastIndex - 1], cost[cost.lastIndex])
}
}
| LC-PS/src/lc_746/Solution.kt | 1622488380 |
package lc_724
class Solution {
fun pivotIndex(nums: IntArray): Int {
var acc = 0
val subSums = IntArray(nums.size) { acc += nums[it]; acc }
if (acc == subSums[0]) return 0
for (i in 1 until subSums.size) {
if (subSums[i - 1] == acc - subSums[i]) return i
}
return -1
}
}
| LC-PS/src/lc_724/Solution.kt | 465628029 |
package lc_189
class Solution {
fun rotate(nums: IntArray, k: Int) {
nums.apply {
val r = k % size
reverse()
reverse(r, size)
reverse(0, r)
}
}
}
| LC-PS/src/lc_189/Solution.kt | 2681810678 |
package lc_383
class Solution {
fun canConstruct(ransomNote: String, magazine: String): Boolean {
val countOf = IntArray(size = 26)
magazine.forEach { ++countOf[it - 'a'] }
ransomNote.forEach {
val i = it - 'a'
if (countOf[i] < 1) return false else --countOf[i]
}
return true
}
}
| LC-PS/src/lc_383/Solution.kt | 3123380047 |
package com.personal.animeshpandey.vocabpro
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.personal.animeshpandey.vocabpro", appContext.packageName)
}
} | DictionaryV2/app/src/androidTest/java/com/personal/animeshpandey/vocabpro/ExampleInstrumentedTest.kt | 905720170 |
package com.personal.animeshpandey.vocabpro
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | DictionaryV2/app/src/test/java/com/personal/animeshpandey/vocabpro/ExampleUnitTest.kt | 3403386521 |
package com.personal.animeshpandey.vocabpro.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/ui/theme/Color.kt | 3544774885 |
package com.personal.animeshpandey.vocabpro.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun VocabProTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/ui/theme/Theme.kt | 1670211613 |
package com.personal.animeshpandey.vocabpro.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/ui/theme/Type.kt | 3743074445 |
package com.personal.animeshpandey.vocabpro.ui
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class DictionaryApp:Application() {
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/ui/DictionaryApp.kt | 1564164455 |
package com.personal.animeshpandey.vocabpro
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.personal.animeshpandey.vocabpro.feature_dictionary.presentation.WordViewModel
import com.personal.animeshpandey.vocabpro.ui.theme.VocabProTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.TextField
import androidx.compose.runtime.remember
import androidx.compose.ui.unit.dp
import com.personal.animeshpandey.vocabpro.feature_dictionary.presentation.WordItem
@AndroidEntryPoint
@OptIn(ExperimentalMaterial3Api::class)
class MainActivity : ComponentActivity() {
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
VocabProTheme {
val vm: WordViewModel = hiltViewModel()
val state = vm.state.value
val snackbarHostState = remember { SnackbarHostState() }
LaunchedEffect(key1 = true) {
vm.eventFlow.collectLatest { event ->
when(event) {
is WordViewModel.UIEvent.ShowSnackbar -> {
snackbarHostState.showSnackbar(
message = event.message
)
}
}
}
}
Scaffold(
snackbarHost = { SnackbarHost(snackbarHostState) }
) {
Box(
modifier = Modifier
.background(MaterialTheme.colorScheme.background)
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
TextField(
value = vm.searchQuery.value,
onValueChange = vm::onSearch,
modifier = Modifier.fillMaxWidth(),
placeholder = {
Text(text = "Search...")
}
)
Spacer(modifier = Modifier.height(16.dp))
LazyColumn(
modifier = Modifier.fillMaxSize()
) {
items(state.wordInfoItems.size) { i ->
val wordInfo = state.wordInfoItems[i]
if(i > 0) {
Spacer(modifier = Modifier.height(8.dp))
}
WordItem(wordInfo = wordInfo)
if(i < state.wordInfoItems.size - 1) {
Divider()
}
}
}
}
}
}
}
}}}
| DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/MainActivity.kt | 3292564772 |
package com.personal.animeshpandey.vocabpro.core
import com.google.gson.Gson
import java.lang.reflect.Type
class GsonParser(
private val gson: Gson
): JSON_Parser {
override fun <T> fromJson(json: String, type: Type): T? {
return gson.fromJson(json, type)
}
override fun <T> toJson(obj: T, type: Type): String? {
return gson.toJson(obj, type)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/core/GSON_Parser.kt | 710079493 |
package com.personal.animeshpandey.vocabpro.core
import java.lang.reflect.Type
interface JSON_Parser {
//to convert to and from JSON Type
fun <T> fromJson(json: String, type: Type): T?
fun <T> toJson(obj: T, type: Type): String?
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/core/JSON_Parser.kt | 2653938576 |
package com.personal.animeshpandey.vocabpro.core
import androidx.room.ProvidedTypeConverter
import androidx.room.TypeConverter
import com.google.gson.reflect.TypeToken
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.Meaning
import androidx.annotation.StringRes
@ProvidedTypeConverter
class converters(private val myjsonparser:JSON_Parser){
@TypeConverter
fun fromMeaningsJSON(json:String):List<Meaning>{
return myjsonparser.fromJson<ArrayList<Meaning>>(
json,
object : TypeToken<ArrayList<Meaning>>(){}.type
)?: emptyList()
}
@TypeConverter
fun toMeaningsJson(meanings: List<Meaning>):String{
return myjsonparser.toJson(
meanings,
object :TypeToken<ArrayList<Meaning>>(){}.type
)?:"[]" //empty json
}
}
typealias SimpleResource = Resource<Unit>
sealed class Resource<T>(val data: T? = null, val message: String? = null) {
class Loading<T>(data: T? = null): Resource<T>(data)
class Success<T>(data: T?): Resource<T>(data)
class Error<T>(message: String, data: T? = null): Resource<T>(data, message)
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/core/Util.kt | 686464885 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.repository
import com.personal.animeshpandey.vocabpro.core.Resource
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.WordDAO
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DictionaryApi
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.repository.WordRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import java.io.IOException
//the repository decides which source of data to use internet, or cache
class WordInfoRepoImpl (
private val api: DictionaryApi,
private val dao: WordDAO
): WordRepository{
override fun getWordInfo(word: String): Flow<Resource<List<WordModel>>> = flow {
emit(Resource.Loading())
val wordinfos = dao.getwordInfos(word).map {it.toWord() }
emit(Resource.Loading(data = wordinfos))
try{
val remotewords = api.getWordInfo(word)
dao.deleteWords(remotewords.map { it.word })
dao.insertWords(remotewords.map { it.toWord()})
}catch (e:retrofit2.HttpException){
emit(Resource.Error(
message = "Oops, something went wrong!",
data = wordinfos
))
}catch (e:IOException){
emit(Resource.Error(
message = "Can't Fetch from servers, check connection!",
data = wordinfos
))
}
val newWordInfos = dao.getwordInfos(word).map{it.toWord()}
emit(Resource.Success(newWordInfos))
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/repository/WordInfoRepoImpl.kt | 3586769420 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.Entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.Meaning
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
@Entity
data class WordEntity(
@PrimaryKey val ID:Int? = null,
val word:String, //this is the name of the word, wordModel is the entire word object
val phonetic:String,
val origin:String,
val meanings:List<Meaning>
){
fun toWord(): WordModel{
return WordModel(
meanings = meanings,
phonetic = phonetic,
word = word,
origin = origin
)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/local_DB/Entity/WordEntity.kt | 1111430795 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.Entity.WordEntity
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
@Dao
interface WordDAO{
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertWords(words:List<WordEntity>)
@Query("DELETE FROM wordentity WHERE word IN(:words)") //tablename should be same as the entitity name which here is wordentity
suspend fun deleteWords(words:List<String>)
@Query("SELECT * FROM wordentity WHERE word LIKE '%' || :word || '%'")
suspend fun getwordInfos(word:String):List<WordEntity>
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/local_DB/WordDAO.kt | 2298972619 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import com.personal.animeshpandey.vocabpro.core.converters
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.Entity.WordEntity
@Database(
entities = [WordEntity::class],
version = 1 //everytime database is update version is incremented
)
@TypeConverters(converters::class)
abstract class WordDB:RoomDatabase() {
abstract val dao: WordDAO
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/local_DB/WordDB.kt | 3141134232 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DTO
data class PhoneticDTO(
val audio: String,
val text: String
) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/remote/DTO/PhoneticDTO.kt | 2812724427 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DTO
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.Meaning
data class MeaningDTO(
val definitions: List<DefinitionDTO>,
val partsOfSpeech:String
){
fun toMeaningModel(): Meaning {
return Meaning(
definitions = definitions.map { it.toDefinitionObject() },
partsOfSpeech = partsOfSpeech
)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/remote/DTO/MeaningDTO.kt | 205957691 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DTO
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.Definition
//DTO Is Data transfer object, it essentially converts the object from transmission friendly unit to a model unit
//we may not need to map all DTO's to a model in our app , it depends on how much functionality we want
data class DefinitionDTO(
val antonyms: List<String>,
val definition: String,
val example: String?, //Some words may not have an example so nullable
val synonyms: List<String>
){
fun toDefinitionObject():Definition{
return Definition(
antonyms = antonyms,
definition = definition,
example = example,
synonyms = synonyms
)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/remote/DTO/DefinitionDTO.kt | 2081413495 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DTO
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.Entity.WordEntity
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
data class WordInfoDto(
val meanings: List<MeaningDTO>,
val origin: String,
val phonetic: String,
val phonetics: List<PhoneticDTO>,
val word: String
) {
fun toWordModel(): WordModel {
//only 4 features of the DTO rather than 5 are used
//only DTO's interact with DTO's
return WordModel(
meanings = meanings.map{it.toMeaningModel()},
origin = origin,
phonetic = phonetic,
word = word
)
}
fun toWordEntity():WordEntity{
return WordEntity(
meanings = meanings.map{it.toMeaningModel()},
origin = origin,
phonetic = phonetic,
word = word
)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/remote/DTO/WordDTO.kt | 1777958607 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DTO.WordInfoDto
import retrofit2.http.GET
import retrofit2.http.Path
interface DictionaryApi {
@GET("/api/v2/entries/en/{word}")
suspend fun getWordInfo(
@Path("word") word: String
): List<WordInfoDto>
companion object {
const val BASE_URL = "https://api.dictionaryapi.dev/"
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/data/remote/DictionaryAPI.kt | 463404582 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.domain.repository
import com.personal.animeshpandey.vocabpro.core.Resource
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
import kotlinx.coroutines.flow.Flow
//THE repository has the job of deciding which source of data to use and forward to the viewmodel
//either use the internet(if avaialble) else caching(the DB we setup)
//implements SSOT , Single source of truth
interface WordRepository{
fun getWordInfo(word:String): Flow<Resource<List<WordModel>>>
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/domain/repository/WordRepository.kt | 3608118669 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model
//val phonetics: List<PhoneticDTO> We dont need a list currently so we dont design a model that we
//it however does get represented in the DTO If we need that feature in the future and we need to make a model out of it
data class WordModel(
val meanings: List<Meaning>,
val origin: String,
val phonetic: String,
val word: String
) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/domain/model/WordModel.kt | 3600706370 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model
data class Meaning(
val definitions:List<Definition>,
val partsOfSpeech:String
) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/domain/model/MeaningModel.kt | 2355072609 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model
data class Definition(
val antonyms: List<String>,
val definition: String,
val example: String?,
val synonyms: List<String>
) | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/domain/model/DefinitionModel.kt | 2148971654 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.domain.usecase
import com.personal.animeshpandey.vocabpro.core.Resource
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.repository.WordRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class GetWordInfo(
private val repository: WordRepository
) {
operator fun invoke(word: String): Flow<Resource<List<WordModel>>> {
if(word.isBlank()) {
return flow { }
}
return repository.getWordInfo(word)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/domain/usecase/GetWordInfo.kt | 2413098504 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.dependencyInjection
import android.app.Application
import androidx.room.Room
import com.google.gson.Gson
import com.personal.animeshpandey.vocabpro.core.GsonParser
import com.personal.animeshpandey.vocabpro.core.converters
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.local_DB.WordDB
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.remote.DictionaryApi
import com.personal.animeshpandey.vocabpro.feature_dictionary.data.repository.WordInfoRepoImpl
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.repository.WordRepository
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.usecase.GetWordInfo
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object WordModule {
@Provides
@Singleton
fun provideGetWordInfoUseCase(repository: WordRepository): GetWordInfo {
return GetWordInfo(repository)
}
@Provides
@Singleton
fun provideWordInfoRepository(
db: WordDB,
api: DictionaryApi
): WordRepository {
return WordInfoRepoImpl(api, db.dao)
}
@Provides
@Singleton
fun provideWordInfoDatabase(app: Application): WordDB {
return Room.databaseBuilder(
app, WordDB::class.java, "word_db"
).addTypeConverter(converters(GsonParser(Gson())))
.build()
}
@Provides
@Singleton
fun provideDictionaryApi(): DictionaryApi {
return Retrofit.Builder()
.baseUrl(DictionaryApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(DictionaryApi::class.java)
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/dependencyInjection/WordModule.kt | 3028347867 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.presentation
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.personal.animeshpandey.vocabpro.core.Resource
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.usecase.GetWordInfo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class WordViewModel @Inject constructor(
private val getWordInfo: GetWordInfo
):ViewModel(){
private val _searchQuery = mutableStateOf("")
val searchQuery: State<String> = _searchQuery
private val _state = mutableStateOf(WordState())
val state: State<WordState> = _state
private val _eventFlow = MutableSharedFlow<UIEvent>()
val eventFlow = _eventFlow.asSharedFlow()
private var searchJob: Job? = null
fun onSearch(query: String) {
_searchQuery.value = query
searchJob?.cancel()
searchJob = viewModelScope.launch {
delay(500L)
getWordInfo(query)
.onEach { result ->
when(result) {
is Resource.Success -> {
_state.value = state.value.copy(
wordInfoItems = result.data ?: emptyList(),
isLoading = false
)
}
is Resource.Error -> {
_state.value = state.value.copy(
wordInfoItems = result.data ?: emptyList(),
isLoading = false
)
_eventFlow.emit(UIEvent.ShowSnackbar(
result.message ?: "Unknown error"
))
}
is Resource.Loading -> {
_state.value = state.value.copy(
wordInfoItems = result.data ?: emptyList(),
isLoading = true
)
}
}
}.launchIn(this)
}
}
sealed class UIEvent {
data class ShowSnackbar(val message: String): UIEvent()
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/presentation/WordViewModel.kt | 2635118951 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.presentation
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.personal.animeshpandey.vocabpro.feature_dictionary.dependencyInjection.WordModule
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
@Composable
fun WordItem(
wordInfo: WordModel,
modifier: Modifier = Modifier
) {
Column(modifier = modifier) {
Text(
text = wordInfo.word,
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = Color.Black
)
Text(text = wordInfo.phonetic, fontWeight = FontWeight.Light)
Spacer(modifier = Modifier.height(16.dp))
Text(text = wordInfo.origin)
wordInfo.meanings.forEach { meaning ->
Text(text = meaning.partsOfSpeech, fontWeight = FontWeight.Bold)
meaning.definitions.forEachIndexed { i, definition ->
Text(text = "${i + 1}. ${definition.definition}")
Spacer(modifier = Modifier.height(8.dp))
definition.example?.let { example ->
Text(text = "Example: $example")
}
Spacer(modifier = Modifier.height(8.dp))
}
Spacer(modifier = Modifier.height(16.dp))
}
}
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/presentation/WordItemComposable.kt | 1772947890 |
package com.personal.animeshpandey.vocabpro.feature_dictionary.presentation
import com.personal.animeshpandey.vocabpro.feature_dictionary.domain.model.WordModel
data class WordState(
val wordInfoItems: List<WordModel> = emptyList(),
val isLoading: Boolean = false
){
} | DictionaryV2/app/src/main/java/com/personal/animeshpandey/vocabpro/feature_dictionary/presentation/WordState.kt | 948204418 |
package com.image.editor
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.image.editor", appContext.packageName)
}
} | Image-editor-tools/app/src/androidTest/java/com/image/editor/ExampleInstrumentedTest.kt | 306445495 |
package com.image.editor
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} | Image-editor-tools/app/src/test/java/com/image/editor/ExampleUnitTest.kt | 766483412 |
package com.image.editor
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.ui.AppBarConfiguration
import com.image.editor.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
private val startForImageFromGalleryResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
if (resultCode == Activity.RESULT_OK) {
takeUriPermission(data?.data?.toString())
val selectedImage = data?.data?.toString()
val intent = Intent(this, ImageEditingActivity::class.java)
intent.putExtra(ImageEditingActivity.KEY_SELECTED_IMAGE, selectedImage)
startForPreviewResult.launch(intent)
} else {
Toast.makeText(this, "Task Cancelled", Toast.LENGTH_SHORT).show()
}
}
private val startForPreviewResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
val resultCode = result.resultCode
val data = result.data
if (resultCode == Activity.RESULT_OK) {
val imagePath = data?.getStringExtra("imagePath")
if(imagePath != null){
binding.ivEditedImage.scaleType = ImageView.ScaleType.CENTER_INSIDE
if (imagePath.isNotEmpty()) {
binding.ivEditedImage.setImageURI(Uri.parse(imagePath))
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnChooseImage.setOnClickListener {
galleryIntent()
}
}
private fun galleryIntent() {
val intent = Intent()
intent.apply {
type = "image/*"
action = Intent.ACTION_OPEN_DOCUMENT
flags = Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
}
startForImageFromGalleryResult.launch(
Intent.createChooser(
intent,
"Select Image"
)
)
}
fun Activity.takeUriPermission(uri: String?) {
if (uri.isNullOrEmpty()) return
try {
contentResolver?.takePersistableUriPermission(
Uri.parse(uri),
Intent.FLAG_GRANT_WRITE_URI_PERMISSION
or Intent.FLAG_GRANT_READ_URI_PERMISSION
)
} catch (securityException: SecurityException) {
Log.e(
"No URI grants given for uri- ($uri). ",
"Proceeding to view image without uri permissions grants"
)
}
}
} | Image-editor-tools/app/src/main/java/com/image/editor/MainActivity.kt | 826507405 |
package com.image.editor
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle
import android.os.ParcelFileDescriptor
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import com.google.android.material.slider.Slider
import com.image.editor.databinding.ActivityImageEditingBinding
import java.io.File
import java.io.FileDescriptor
import java.io.FileOutputStream
import java.io.IOException
import java.util.UUID
class ImageEditingActivity : AppCompatActivity() {
companion object {
val KEY_SELECTED_IMAGE = "selected_image-path"
}
lateinit var binding: ActivityImageEditingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityImageEditingBinding.inflate(layoutInflater)
setContentView(binding.root)
val croppedOilPatternFilePath = intent.getStringExtra(KEY_SELECTED_IMAGE)
val bitmap = uriToBitmap(Uri.parse(croppedOilPatternFilePath))
binding.customView.post {
bitmap?.let {
binding.customView.setImageBitmap(
Bitmap.createScaledBitmap(
it,
binding.customView.width / 2,
binding.customView.height / 2,
true
)
)
}
}
binding.btnSave.setOnClickListener {
if (binding.customView.getCurrentMode() == CustomImageEditingView.Mode.CROP) {
binding.customView.cropAndSetImage()
resetAllMode()
binding.btnMove.performClick()
} else {
saveImage()
}
}
binding.sliderOpacity.addOnChangeListener { _, value, _ ->
binding.customView.alpha = 1 - value
}
binding.sliderSkew.addOnSliderTouchListener(object : Slider.OnSliderTouchListener {
override fun onStartTrackingTouch(p0: Slider) {
}
override fun onStopTrackingTouch(p0: Slider) {
binding.customView.skewImageUpdate()
}
})
binding.sliderSkew.addOnChangeListener { _, value, _ ->
Log.d("Value", "$value")
if (binding.cbVertical.isChecked) {
binding.customView.skewImage(0f, value, binding.cbTopBottom.isChecked)
} else {
binding.customView.skewImage(value, 0f, binding.cbTopBottom.isChecked)
}
}
binding.btnFlip.setOnClickListener {
resetAllMode()
binding.btnFlip.setColorFilter(getColor(R.color.white), PorterDuff.Mode.SRC_ATOP)
binding.btnFlip.setBackgroundColor(getColor(R.color.primary))
binding.customView.flipHorizontally()
}
binding.btnResize.setOnClickListener {
resetAllMode()
binding.btnResize.setColorFilter(getColor(R.color.white))
binding.btnResize.setBackgroundColor(getColor(R.color.primary))
binding.customView.setMode(CustomImageEditingView.Mode.RESIZE)
}
binding.btnMove.setOnClickListener {
resetAllMode()
binding.btnMove.setColorFilter(getColor(R.color.white))
binding.btnMove.setBackgroundColor(getColor(R.color.primary))
binding.customView.setMode(CustomImageEditingView.Mode.DRAG)
}
binding.btnCrop.setOnClickListener {
resetAllMode()
binding.btnCrop.setColorFilter(getColor(R.color.white))
binding.btnCrop.setBackgroundColor(getColor(R.color.primary))
binding.customView.setMode(CustomImageEditingView.Mode.CROP)
binding.btnSave.text = "Crop"
}
binding.btnSkew.setOnClickListener {
resetAllMode()
binding.groupSkew.visibility = View.VISIBLE
binding.btnSkew.setColorFilter(getColor(R.color.white))
binding.btnSkew.setBackgroundColor(getColor(R.color.primary))
binding.customView.setMode(CustomImageEditingView.Mode.SKEW)
}
binding.btnAlpha.setOnClickListener {
resetAllMode()
binding.sliderOpacity.visibility = View.VISIBLE
binding.btnAlpha.setColorFilter(getColor(R.color.white))
binding.btnAlpha.setBackgroundColor(getColor(R.color.primary))
binding.customView.setMode(CustomImageEditingView.Mode.ALPHA)
}
}
private fun saveImage() {
//preparing bitmap image
binding.sliderOpacity.visibility = View.GONE
binding.btnMove.performClick()
try {
val bitmap = binding.customView.getBitmap()
if (bitmap != null) {
// Crop the bitmap
val path = saveBitmapAndGetPath(applicationContext, bitmap)
if (path != null) {
val intent = Intent()
intent.putExtra("imagePath", path.toString())
setResult(RESULT_OK, intent)
}
}
} catch (e: Exception) {
Toast.makeText(this, "Error while generation oil pattern", Toast.LENGTH_SHORT).show()
}
finish()
}
fun View.getBitmap(): Bitmap? {
val b = Bitmap.createBitmap(
width,
height,
Bitmap.Config.ARGB_8888
)
val c = Canvas(b)
layout(left, top, right, bottom)
draw(c)
return b
}
fun Activity.uriToBitmap(selectedFileUri: Uri): Bitmap? {
return try {
val parcelFileDescriptor: ParcelFileDescriptor =
contentResolver.openFileDescriptor(selectedFileUri, "r")!!
val fileDescriptor: FileDescriptor = parcelFileDescriptor.fileDescriptor
val image = BitmapFactory.decodeFileDescriptor(fileDescriptor)
parcelFileDescriptor.close()
image
} catch (e: IOException) {
null
}
}
fun saveBitmapAndGetPath(context: Context, bitmap: Bitmap): Uri? {
val cacheDirectory = File(context.cacheDir, "images")
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs()
}
var bitmapPath: File? = null
val fileName = UUID.randomUUID().toString() + ".png"
try {
bitmapPath = File(cacheDirectory, fileName)
bitmapPath.createNewFile()
val stream =
FileOutputStream("$bitmapPath")
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
stream.close()
} catch (e: IOException) {
Log.e("TAG", "saving bitmap error: $bitmap", e)
}
return bitmapPath?.toUri()
}
private fun resetAllMode() {
binding.groupSkew.visibility = View.GONE
binding.btnFlip.setColorFilter(getColor(R.color.black))
binding.btnMove.setColorFilter(getColor(R.color.black))
binding.btnSkew.setColorFilter(getColor(R.color.black))
binding.btnResize.setColorFilter(getColor(R.color.black))
binding.btnCrop.setColorFilter(getColor(R.color.black))
binding.btnAlpha.setColorFilter(getColor(R.color.black))
binding.btnFlip.background = null
binding.btnMove.background = null
binding.btnSkew.background = null
binding.btnResize.background = null
binding.btnCrop.background = null
binding.btnAlpha.background = null
binding.sliderOpacity.visibility = View.GONE
binding.btnSave.text = "Save"
}
} | Image-editor-tools/app/src/main/java/com/image/editor/ImageEditingActivity.kt | 3246751151 |
package com.image.editor
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
fun Canvas.drawGridLines(imageRect: RectF, paint: Paint) {
val minGridSize = 1 // Minimum grid size
val maxGridLines = 5 // Maximum number of grid lines
// Calculate the ideal grid size based on the dimensions of the imageRect
val idealGridSizeX = imageRect.width() / maxGridLines
val idealGridSizeY = imageRect.height() / maxGridLines
// Determine the final grid size as the maximum of the minimum grid size and the ideal grid size
val gridSizeX = Math.max(minGridSize, idealGridSizeX.toInt())
val gridSizeY = Math.max(minGridSize, idealGridSizeY.toInt())
// Draw vertical grid lines
var x = imageRect.left + gridSizeX
while (x < imageRect.right) {
drawLine(x, imageRect.top, x, imageRect.bottom, paint)
x += gridSizeX
}
// Draw horizontal grid lines
var y = imageRect.top + gridSizeY
while (y < imageRect.bottom) {
drawLine(imageRect.left, y, imageRect.right, y, paint)
y += gridSizeY
}
}
fun Canvas.drawHandles(imageRect: RectF, paint: Paint, handleLength: Float = 70f) {
// Draw top-left corner L shape
drawLine(imageRect.left, imageRect.top, imageRect.left, imageRect.top + handleLength, paint)
drawLine(imageRect.left, imageRect.top, imageRect.left + handleLength, imageRect.top, paint)
// Draw top-right corner L shape
drawLine(imageRect.right, imageRect.top, imageRect.right, imageRect.top + handleLength, paint)
drawLine(imageRect.right, imageRect.top, imageRect.right - handleLength, imageRect.top, paint)
// Draw bottom-left corner L shape
drawLine(
imageRect.left,
imageRect.bottom,
imageRect.left,
imageRect.bottom - handleLength,
paint
)
drawLine(
imageRect.left,
imageRect.bottom,
imageRect.left + handleLength,
imageRect.bottom,
paint
)
// Draw bottom-right corner L shape
drawLine(
imageRect.right,
imageRect.bottom,
imageRect.right,
imageRect.bottom - handleLength,
paint
)
drawLine(
imageRect.right,
imageRect.bottom,
imageRect.right - handleLength,
imageRect.bottom,
paint
)
// Draw handle line at the center of the top side
val topCenterX = (imageRect.left + imageRect.right) / 2
val topCenterY = imageRect.top
drawLine(
topCenterX - handleLength / 2,
topCenterY,
topCenterX + handleLength / 2,
topCenterY,
paint
)
// Draw handle line at the center of the bottom side
val bottomCenterX = (imageRect.left + imageRect.right) / 2
val bottomCenterY = imageRect.bottom
drawLine(
bottomCenterX - handleLength / 2,
bottomCenterY,
bottomCenterX + handleLength / 2,
bottomCenterY,
paint
)
// Draw handle line at the center of the left side
val leftCenterX = imageRect.left
val leftCenterY = (imageRect.top + imageRect.bottom) / 2
drawLine(
leftCenterX,
leftCenterY - handleLength / 2,
leftCenterX,
leftCenterY + handleLength / 2,
paint
)
// Draw handle line at the center of the right side
val rightCenterX = imageRect.right
val rightCenterY = (imageRect.top + imageRect.bottom) / 2
drawLine(
rightCenterX,
rightCenterY - handleLength / 2,
rightCenterX,
rightCenterY + handleLength / 2,
paint
)
}
| Image-editor-tools/app/src/main/java/com/image/editor/CanvasExt.kt | 3431546761 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.