• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

dkandalov/kotlin-99: Ninety-Nine Problems in Kotlin

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

dkandalov/kotlin-99

开源软件地址(OpenSource Url):

https://github.com/dkandalov/kotlin-99

开源编程语言(OpenSource Language):

Kotlin 100.0%

开源软件介绍(OpenSource Introduction):

Ninety-Nine Kotlin Problems

Build Status

Table of Contents

Introduction

This is an adaptation of Ninety-Nine Scala Problems by Phil Gold which itself is an adaptation of the Ninety-Nine Prolog Problems written by Werner Hett at the Berne University of Applied Sciences in Berne, Switzerland. Some problems have been altered to be more amenable to programming in Kotlin.

You might want to do these problems if you want to learn Kotlin, are interested in the problems described below, or both. The main reason to prefer this to using websites like hackerrank.com and codewars.com is that there is no vendor lock-in and no hidden agenda pursued by the website owner.

The suggested workflow is to solve a problem yourself and then compare solution to the one provided.
Solutions are available by clicking on the link at the beginning of the problem description. Your goal should be to find the most elegant solution to the given problems. Efficiency is important, but clarity is even more crucial. Some of the (easy) problems can be trivially solved using built-in functions. However, in these cases, you can learn more if you try to find your own solution.

The problems have different levels of difficulty. Those marked with a single asterisk * are easy. If you have successfully solved the preceding problems, you might be able to solve them within a few (say 15) minutes. Problems marked with two asterisks ** are of intermediate difficulty and might take about 30-90 minutes to solve. Problems marked with three asterisks *** are more difficult. You may need more time (i.e. a few hours or more) to find a good solution. Please note that levels of difficulty is just a guess and assumes you are somewhat familiar with the problem domain. It is perfectly ok if some of them take longer. Overall, the goal is to learn, not to finish "on time".

You might notice that there are less than 99 problems. This is because numbering of original problems was wrong. It was kept here for consistency with 99 problems in other programming languages.

The first 50 or so problems are easy. If this is boring for you, feel free to jump to Binary Trees.

All contributions are welcome (including alternative solutions for problems which already have a solution).

Lists

P01 (*) Find the last element of a list.

Example:

> last(listOf(1, 1, 2, 3, 5, 8))
8

P02 (*) Find the last but one element of a list.

Example:

> penultimate(listOf(1, 1, 2, 3, 5, 8))
5

P03 (*) Find the Nth element of a list.

By convention, the first element in the list is element 0. Example:

> nth(2, listOf(1, 1, 2, 3, 5, 8))
2

P04 (*) Find the number of elements of a list.

Example:

> length(listOf(1, 1, 2, 3, 5, 8))
6

P05 (*) Reverse a list.

Example:

> reverse(listOf(1, 1, 2, 3, 5, 8))
[8, 5, 3, 2, 1, 1]

P06 (*) Find out whether a list is a palindrome.

Example:

> isPalindrome(listOf(1, 2, 3, 2, 1))
true

P07 (*) Flatten a nested list structure.

Example:

> flatten(listOf(listOf(1, 1), 2, listOf(3, listOf(5, 8))))
[1, 1, 2, 3, 5, 8]

P08 (*) Eliminate consecutive duplicates of list elements.

If a list contains repeated elements, they should be replaced with a single copy of the element. The order of the elements should not be changed. Example:

> compress("aaaabccaadeeee".toList())
[a, b, c, a, d, e]

P09 (*) Pack consecutive duplicates of list elements into sublists.

If a list contains repeated elements, they should be placed in separate sublists. Example:

> pack("aaaabccaadeeee".toList())
[[a, a, a, a], [b], [c, c], [a, a], [d], [e, e, e, e]]

P10 (*) Run-length encoding of a list.

Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E. Example:

> encode("aaaabccaadeeee".toList())
[(4, a), (1, b), (2, c), (2, a), (1, d), (4, e)]

P11 (*) Modified run-length encoding.

Modify the result of problem P10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N, E) terms. Example:

> encodeModified("aaaabccaadeeee".toList())
[(4, a), b, (2, c), (2, a), d, (4, e)]

P12 (*) Decode a run-length encoded list.

Given a run-length code list generated as specified in the problem P10, construct its uncompressed version. Example:

> decode(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e)))
[a, a, a, a, b, c, c, a, a, d, e, e, e, e]

P13 (*) Run-length encoding of a list (direct solution).

Implement the so-called run-length encoding data compression method directly. I.e. don't use other methods you've written (like P09's pack); do all the work directly. Example:

> encodeDirect("aaaabccaadeeee".toList())
[(4, a), (1, b), (2, c), (2, a), (1, d), (4, e)]

P14 (*) Duplicate the elements of a list.

Example:

> duplicate("abccd".toList())
[a, a, b, b, c, c, c, c, d, d]

P15 (*) Duplicate the elements of a list a given number of times.

Example:

> duplicateN(3, "abccd".toList())
[a, a, a, b, b, b, c, c, c, c, c, c, d, d, d]

P16 (*) Drop every Nth element from a list.

Example:

> drop(3, "abcdefghijk".toList())
[a, b, d, e, g, h, j, k]

P17 (*) Split a list into two parts.

The length of the first part is given. Use a Pair for your result. Example:

> split(3, "abcdefghijk".toList())
([a, b, c], [d, e, f, g, h, i, j, k])

P18 (*) Extract a slice from a list.

Given two indices, I and K, the slice is the list containing the elements from and including the Ith element up to but not including the Kth element of the original list. Start counting the elements with 0. Example:

> slice(3, 7, "abcdefghijk".toList())
[d, e, f, g]

P19 (*) Rotate a list N places to the left.

Examples:

> rotate(3, "abcdefghijk".toList())
[d, e, f, g, h, i, j, k, a, b, c]

> rotate(-2, "abcdefghijk".toList())
[j, k, a, b, c, d, e, f, g, h, i]

P20 (*) Remove the Kth element from a list.

Return the list and the removed element in a Tuple. Elements are numbered from 0. Example:

> removeAt(1, "abcd".toList())
([a, c, d], b)

P21 (*) Insert an element at a given position into a list.

Example:

> insertAt('X', 1, "abcd".toList())
[a, X, b, c, d]

P22 (*) Create a list containing all integers within a given range.

Example:

> range(4, 9)
[4, 5, 6, 7, 8, 9]

P23 (*) Extract a given number of randomly selected elements from a list.

Make sure there is a way to produce deterministic results. Example:

> randomSelect(3, "abcdefgh".toList())
[c, h, f]

P24 (*) Lotto: Draw N different random numbers from the set 1..M.

Make sure there is a way to produce deterministic results. Example:

> lotto(3, 49)
[32, 28, 8]

P25 (*) Generate a random permutation of the elements of a list.

Make sure there is a way to produce deterministic results. Hint: Use the solution of problem P23. Example:

> randomPermute("abcdef".toList())
[d, b, e, f, a, c]

P26 (**) Generate the combinations of K distinct objects chosen from the N elements of a list.

In how many ways can a committee of 3 be chosen from a group of 12 people? There are C(12,3) = 220 possibilities, where C(N,K) denotes binomial coefficient. For pure mathematicians, this result may be great. But we want to really generate all the possibilities. Example:

> combinations(3, "abcde".toList())
[[c, b, a], [d, b, a], [e, b, a], [d, c, a], [e, c, a], [e, d, a], [d, c, b], [e, c, b], [e, d, b], [e, d, c]]

P27 (**) Group the elements of a set into disjoint subsets.

a) In how many ways can a group of 9 people work in 3 disjoint subgroups of 2, 3 and 4 persons? Write a function that generates all the possibilities. Example:

> group3(listOf("Aldo", "Beat", "Carla", "David", "Evi", "Flip", "Gary", "Hugo", "Ida"))
[[["Ida", "Hugo", "Gary", "Flip"], ["Evi", "David", "Carla"], ["Beat", "Aldo"]], ...

b) Generalize the above predicate in a way that we can specify a list of group sizes and the predicate will return a list of groups. Example:

> group(listOf(2, 2, 5), listOf("Aldo", "Beat", "Carla", "David", "Evi", "Flip", "Gary", "Hugo", "Ida"))
[[["Ida", "Hugo", "Gary", "Flip", "Evi"], ["David", "Carla"], ["Beat", "Aldo"]], ...

Note that we do not want permutations of the group members, i.e. [[Aldo, Beat], ...]] is the same solution as [[Beat, Aldo], ...]. However, [[Aldo, Beat], [Carla, David], ...] and [[Carla, David], [Aldo, Beat], ...] are considered to be different solutions.

You may find more about this combinatorial problem in a good book on discrete mathematics under the term multinomial coefficients.

P28 (*) Sorting a list of lists according to length of sublists.

a) We suppose that a list contains elements that are lists themselves. The objective is to sort elements of the list according to their length. E.g. short lists first, longer lists later, or vice versa. Example:

> lengthSort(listOf("abc".toList(), "de".toList(), "fgh".toList(), "de".toList(), "ijkl".toList(), "mn".toList(), "o".toList()))
[[o], [d, e], [d, e], [m, n], [a, b, c], [f, g, h], [i, j, k, l]]

b) Again, we suppose that a list contains elements that are lists themselves. But this time the objective is to sort elements according to their length frequency; i.e. lists with rare lengths are placed first, others with more frequent lengths come later. Example:

> lengthFreqSort(listOf("abc".toList(), "de".toList(), "fgh".toList(), "de".toList(), "ijkl".toList(), "mn".toList(), "o".toList()))
[[i, j, k, l], [o], [a, b, c], [f, g, h], [d, e], [d, e], [m, n]]

Note that in the above example, the first two lists in the result have length 4 and 1 and both lengths appear just once. The third and fourth lists have length 3 and there are two list of this length. Finally, the last three lists have length 2. This is the most frequent length.

Arithmetic

P31 (*) Determine whether a given integer number is prime.

> 7.isPrime()
true

P32 (*) Determine the greatest common divisor of two positive integer numbers.

Use Euclid's algorithm.

> gcd(36, 63)
9

P33 (*) Determine whether two positive integer numbers are coprime.

Two numbers are coprime if their greatest common divisor equals 1.

> 35.isCoprimeTo(64)
true

P34 (*) Calculate Euler's totient function phi(m).

Euler's so-called totient function phi(m) is defined as the number of positive integers r (1 <= r <= m) that are coprime to m.

> 10.totient()
4

P35 (*) Determine prime factors of a given positive integer.

Construct a list containing prime factors in ascending order.

> 315.primeFactors()
[3, 3, 5, 7]

P36 (*) Determine the prime factors of a given positive integer (2).

Construct a list containing prime factors and their multiplicity.

> 315.primeFactorMultiplicity()
[(3, 2), (5, 1), (7, 1)]

P37 (*) Calculate Euler's totient function phi(m) (improved).

See problem P34 for the definition of Euler's totient function. If the list of the prime factors of a number m is known in the form of problem P36, then the function phi(m) can be efficiently calculated as follows: Let [[p1, m1], [p2, m2], [p3, m3], ...] be the list of prime factors (and their multiplicities) of a given number m. Then phi(m) can be calculated with the following formula: phi(m) = (p1-1)*p1^(m1-1) * (p2-1)*p2^(m2-1) * (p3-1)*p3^(m3-1) * ...


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap