How to Use Kotlin to Solve Coding Problems

I have talked to many Android developers, and most of them are excited about Kotlin. So am I. When I just started learning Kotlin, I was solving Kotlin Koans, and along with other great features, I was impressed with the power of functions for performing operations on collections. Since then, I spent three years writing Kotlin code but rarely utilised all the potential of the language.

During this year, I did more than a hundred coding problems on Leetcode in Java. I didn’t switch to Kotlin because I know the syntax of Java 6 so well, that I could effortlessly write code without autocompletion and syntax highlighting. But I didn’t keep track of new Java features, as Android support of Java SDK lagged many versions behind. I didn’t switch to Kotlin for solving problems right away.

Although I was writing Kotlin code for several years, I felt that I need to make an extra cognitive effort to get the syntax and the language constructions right. Solving algorithmic problems, especially under time pressure, is very different from Android app development. Still, the more I learned about Kotlin, the more I realised how many powerful features I’m missing, and how much boilerplate code I need to write.

One day, I have decided that I need to move on, so I started a new session in Leetcode and switched the compiler to Kotlin. I solved just a few easy problems, but I already feel that I have something to share.

Loops

Let’s start with loops. Let’s say, you have an

IntArray

of 10 elements

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

and you want to print

123456789
val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in (1 until array.size)) {
  print(array[index])
}
(1 until array.size)

is an

IntRange

a class that represents a range of values of type

Int

The first element in this range is

1

and the last one is

9

as we used

until

to exclude the last value. We don’t want to get

ArrayIndexOutOfBoundsException

right?

But what if we want to print all the elements of the array, except the element at index 5? Like this

012346789

Let’s get a bit more Kotliney then writing an

if

statement in the loop.

val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in array.indices - 5) {
  print(array[index])
}
array.indices

returns the range of valid indices for the array. In this case

array.indices

represent

IntRange

of

(0..9)

Making

(0..9) - 5

will result in

[0, 1, 2, 3, 4, 6, 7, 8, 9]

This is exactly what we need.

Kotlin also provides an ability to iterate from the greater number down to the smaller number using

downTo

The iteration step size can also be changed using

step
val array = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
for(index in array.size - 1 downTo 1 step 2) {
  print(array[index])
}

The code above with result in

97531

Remove Vowels from a String

It’s problem number 1119 on Leetcode.

Given a string S, remove the vowels ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ from it, and return the new string.

Even in Java there is a 1 line regex solution, but my intuition was the following:

1. Create a StringBuilder

2. Iterate over characters, and if the current character is not a vowel, append it to the StringBuilder

3. Return String from the StringBuilder

public String removeVowels(String S) {
  StringBuilder sb = new StringBuilder();  
  for(char s: S.toCharArray()) {
    if(s != 'a' && s != 'e' && s != 'i' && s !='o' && s != 'u') {
      sb.append(s);  
    }
  }
  return sb.toString();
}

What about Kotlin? More idiomatic way is to use

filter()

or

filterNot()
fun removeVowels(S: String): String {
  val vowels = setOf('a', 'e', 'i', 'o', 'u')
  return S.filter { it !in vowels }
}
filter {predicate: (Char) -> Boolean}

returns a string containing only those characters from the original string that match the given predicate.

But instead of inverting

!in

let’s use

filterNot()
fun removeVowels(S: String): String {
  val vowels = setOf('a', 'e', 'i', 'o', 'u')
  return S.filterNot { it in vowels }
}

That was simple even for a beginner. Let’s move on to something a bit more sophisticated.

Running Sum of 1d Array

It’s another easy problem from Leetcode. Number 1480.

Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums.

Input: nums = [1,2,3,4]

Output: [1,3,6,10]

Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

So we need to iterate over the array, adding the value at the current index to the running sum, and put it to the same index in the result array.

Is there something in Kotlin to help us with the running sum? Well, there’s different variations of

fold()

and

reduce()

operations.

Here’s a good explanation of those functions. But since Kotlin 1.4 there’s even more:

runningFold()

and

runningReduce()

As we want to start with the first element and return an array, it looks like

runningReduce()

is what we need. Let’s check its signature.

/**
 * Returns a list containing successive accumulation values generated by applying [operation] from left to right
 * to each element and current accumulator value that starts with the first element of this array.
 * 
 * @param [operation] function that takes current accumulator value and an element, and calculates the next accumulator value.
 * 
 * @sample samples.collections.Collections.Aggregates.runningReduce
 */
@SinceKotlin("1.4")
@kotlin.internal.InlineOnly
public inline fun IntArray.runningReduce(operation: (acc: Int, Int) -> Int): List<Int>

Sounds a bit too complex, but it will make sense when you’ll see an example.

fun runningSum(nums: IntArray): IntArray {
  return nums.runningReduce { sum, element -> sum + element }.toIntArray()
}

This is the whole solution to the running sum problem using Kotlin

runningReduce()

function.

sum

starts with the first

element

in the array, element represens the current element. In lambda, we calculate the value of the next

sum

Oh… I guess my explanation isn’t making it more clear that a doc. Let’s just print out the values of the

sum

and the

element

at each step:

sum: 1; element: 2; sum + element: 3
sum: 3; element: 3; sum + element: 6
sum: 6; element: 4; sum + element: 10
sum: 10; element: 5; sum + element: 15

And the array we return is

[1, 3, 6, 10, 15]

There is no

sum + element: 1

I didn’t miss the line. The thing is that

runningReduce

as we see in the doc, takes the first value as the initial accumulator.

Unfortunately, Leetcode doesn’t support Kotlin 1.4 yet, so the code above might not compile.

#kotlin #programming #android #java #mobile-apps

What is GEEK

Buddha Community

How to Use Kotlin to Solve Coding Problems
Vincent Lab

Vincent Lab

1605176864

How to do Problem Solving as a Developer

In this video, I will be talking about problem-solving as a developer.

#problem solving skills #problem solving how to #problem solving strategies #problem solving #developer

Tyrique  Littel

Tyrique Littel

1604008800

Static Code Analysis: What It Is? How to Use It?

Static code analysis refers to the technique of approximating the runtime behavior of a program. In other words, it is the process of predicting the output of a program without actually executing it.

Lately, however, the term “Static Code Analysis” is more commonly used to refer to one of the applications of this technique rather than the technique itself — program comprehension — understanding the program and detecting issues in it (anything from syntax errors to type mismatches, performance hogs likely bugs, security loopholes, etc.). This is the usage we’d be referring to throughout this post.

“The refinement of techniques for the prompt discovery of error serves as well as any other as a hallmark of what we mean by science.”

  • J. Robert Oppenheimer

Outline

We cover a lot of ground in this post. The aim is to build an understanding of static code analysis and to equip you with the basic theory, and the right tools so that you can write analyzers on your own.

We start our journey with laying down the essential parts of the pipeline which a compiler follows to understand what a piece of code does. We learn where to tap points in this pipeline to plug in our analyzers and extract meaningful information. In the latter half, we get our feet wet, and write four such static analyzers, completely from scratch, in Python.

Note that although the ideas here are discussed in light of Python, static code analyzers across all programming languages are carved out along similar lines. We chose Python because of the availability of an easy to use ast module, and wide adoption of the language itself.

How does it all work?

Before a computer can finally “understand” and execute a piece of code, it goes through a series of complicated transformations:

static analysis workflow

As you can see in the diagram (go ahead, zoom it!), the static analyzers feed on the output of these stages. To be able to better understand the static analysis techniques, let’s look at each of these steps in some more detail:

Scanning

The first thing that a compiler does when trying to understand a piece of code is to break it down into smaller chunks, also known as tokens. Tokens are akin to what words are in a language.

A token might consist of either a single character, like (, or literals (like integers, strings, e.g., 7Bob, etc.), or reserved keywords of that language (e.g, def in Python). Characters which do not contribute towards the semantics of a program, like trailing whitespace, comments, etc. are often discarded by the scanner.

Python provides the tokenize module in its standard library to let you play around with tokens:

Python

1

import io

2

import tokenize

3

4

code = b"color = input('Enter your favourite color: ')"

5

6

for token in tokenize.tokenize(io.BytesIO(code).readline):

7

    print(token)

Python

1

TokenInfo(type=62 (ENCODING),  string='utf-8')

2

TokenInfo(type=1  (NAME),      string='color')

3

TokenInfo(type=54 (OP),        string='=')

4

TokenInfo(type=1  (NAME),      string='input')

5

TokenInfo(type=54 (OP),        string='(')

6

TokenInfo(type=3  (STRING),    string="'Enter your favourite color: '")

7

TokenInfo(type=54 (OP),        string=')')

8

TokenInfo(type=4  (NEWLINE),   string='')

9

TokenInfo(type=0  (ENDMARKER), string='')

(Note that for the sake of readability, I’ve omitted a few columns from the result above — metadata like starting index, ending index, a copy of the line on which a token occurs, etc.)

#code quality #code review #static analysis #static code analysis #code analysis #static analysis tools #code review tips #static code analyzer #static code analysis tool #static analyzer

Vincent Lab

Vincent Lab

1605176646

How to Ask a Good Question on the Internet as a Programmer

In this video, I will be talking about how to ask for help as a developer.

#problem solving skills #problem solving how to #coding interviews #problem solving #how to ask a good question

Samanta  Moore

Samanta Moore

1621137960

Guidelines for Java Code Reviews

Get a jump-start on your next code review session with this list.

Having another pair of eyes scan your code is always useful and helps you spot mistakes before you break production. You need not be an expert to review someone’s code. Some experience with the programming language and a review checklist should help you get started. We’ve put together a list of things you should keep in mind when you’re reviewing Java code. Read on!

1. Follow Java Code Conventions

2. Replace Imperative Code With Lambdas and Streams

3. Beware of the NullPointerException

4. Directly Assigning References From Client Code to a Field

5. Handle Exceptions With Care

#java #code quality #java tutorial #code analysis #code reviews #code review tips #code analysis tools #java tutorial for beginners #java code review

Houston  Sipes

Houston Sipes

1604088000

How to Find the Stinky Parts of Your Code (Part II)

There are more code smells. Let’s keep changing the aromas. We see several symptoms and situations that make us doubt the quality of our development. Let’s look at some possible solutions.

Most of these smells are just hints of something that might be wrong. They are not rigid rules.

This is part II. Part I can be found here.

Code Smell 06 - Too Clever Programmer

The code is difficult to read, there are tricky with names without semantics. Sometimes using language’s accidental complexity.

_Image Source: NeONBRAND on _Unsplash

Problems

  • Readability
  • Maintainability
  • Code Quality
  • Premature Optimization

Solutions

  1. Refactor the code
  2. Use better names

Examples

  • Optimized loops

Exceptions

  • Optimized code for low-level operations.

Sample Code

Wrong

function primeFactors(n){
	  var f = [],  i = 0, d = 2;  

	  for (i = 0; n >= 2; ) {
	     if(n % d == 0){
	       f[i++]=(d); 
	       n /= d;
	    }
	    else{
	      d++;
	    }     
	  }
	  return f;
	}

Right

function primeFactors(numberToFactor){
	  var factors = [], 
	      divisor = 2,
	      remainder = numberToFactor;

	  while(remainder>=2){
	    if(remainder % divisor === 0){
	       factors.push(divisor); 
	       remainder = remainder/ divisor;
	    }
	    else{
	      divisor++;
	    }     
	  }
	  return factors;
	}

Detection

Automatic detection is possible in some languages. Watch some warnings related to complexity, bad names, post increment variables, etc.

#pixel-face #code-smells #clean-code #stinky-code-parts #refactor-legacy-code #refactoring #stinky-code #common-code-smells