Skip to content

Instantly share code, notes, and snippets.

@nieldeokar
Last active October 18, 2024 04:12
Show Gist options
  • Save nieldeokar/770b85ee296a9675e3cbbd63347981a5 to your computer and use it in GitHub Desktop.
Save nieldeokar/770b85ee296a9675e3cbbd63347981a5 to your computer and use it in GitHub Desktop.
Boilerplate code snippets.

Boilerplate

contains common code snippets.

Stack

val stack = ArrayDeque<Int>()

stack.addFirst(10) // push to top
val topElement = stack.first() // peek top 
// Popping elements from the stack
val poppedElement = stack.removeFirst() // pop() - throws exception

Queue

val queue = ArrayDeque<Int>()

queue.addLast(10) // push
val frontElement = queue.first() // peek 
val dequeuedElement = queue.removeFirst() // poll() remove front of the queue

Priority Queue

class Task(val name: String, val priority: Int)
// MinHeap
val taskQueue = PriorityQueue<Task> { task1, task2 ->
  task1.priority - task2.priority
} 
// MaxHeap
val taskQueue = PriorityQueue<Task> { task1, task2 ->
  task2.priority - task1.priority
} 
val taskQueue = PriorityQueue<Int> { a, b ->  b - a } 

// Add tasks to the priority queue
taskQueue.offer(Task("Task with priority 2", 2))
val task = taskQueue.poll()

Sorting kotlin

inplace

val nums = mutableListOf(3, 1, 7, 2, 8, 6)

val sortedNums = nums.sorted() // inplace
val sortedDescending = nums.sortedDescending() // inplace

nums.sortBy { it } // inplace

Returns new list

val newList = nums.sortedBy { it.month }

Sort by first and then second

val newList = myDates.sortWith(compareBy { it.month }.thenBy { it.day })

Directions array

val dirs = arrayOf(intArrayOf(0,1), intArrayOf(1,0),intArrayOf(0,-1),intArrayOf(-1,0))

val dirs = arrayOf(intArrayOf(0,1),intArrayOf(1,1), intArrayOf(1,0), intArrayOf(1,-1),intArrayOf(0,-1),intArrayOf(-1,-1),intArrayOf(-1,0), intArrayOf(-1,1))

int[][] dirs = {{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1},{-1,0},{-1,1}};

Android Libraries

coroutines:

implementation 'androidx.fragment:fragment:1.4.1'
implementation 'androidx.fragment:fragment-ktx:1.4.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.0-rc01'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3'
implementation 'com.squareup.retrofit2:converter-scalars:2.7.1'

reading response from http connection

fun getData(url: String) : Result<String> {

        val urlObj = URL(url)
        (urlObj.openConnection() as? HttpURLConnection)?.run {
            requestMethod = "GET"
            val reader = BufferedReader(InputStreamReader(inputStream))
            val result = StringBuffer()
            var line: String?
            while (reader.readLine().also { line = it } != null) {
                result.append(line)
            }

            return Result.Success(result.toString())
        }
        return Result.Error(Exception("Cannot open HttpURLConnection"))
    }
    }
    
    sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}
        

Reverse array

void reverse(int[] nums){
    int i = 0;
    int j = nums.length - 1;
    while(i < j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

PriorityQueue with Key Value Pair

// usage - PriorityQueue<MapTypePQ<Integer, int[]>> maxQue = new PriorityQueue<>((a,b) -> b.key - a.key);
// PriorityQueue<MapTypePQ<Integer, int[]>> minQue = new PriorityQueue<>((a,b) -> a.key - b.key);

class MapTypePQ<T,K> {
        public T key;
        public K value;
        
        public MapTypePQ(T key, K value){
            this.key = key;
            this.value = value;
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment