├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.sbt ├── project ├── build.properties └── plugins.sbt └── src ├── main └── scala │ └── org │ └── questions │ ├── arrays │ ├── ArrayMaxSumNonConsecutive.scala │ ├── LongestIncreasing.scala │ ├── TwoSum.scala │ └── readme.md │ ├── fibonacci │ ├── Fibonacci.scala │ ├── Iterative.scala │ ├── Recursive.scala │ ├── TailRecursion.scala │ └── readme.md │ ├── fill │ ├── Canvas.scala │ ├── DrawUtils.scala │ └── readme.md │ └── strings │ ├── ParenthesesValidator.scala │ ├── WildCardMatching.scala │ └── readme.md └── test └── scala └── org └── questions ├── FibonacciTest.scala ├── arrays ├── ArrayMaxSumNonConsecutiveTest.scala ├── LongestIncreasingTest.scala └── TwoSumTest.scala ├── fill └── CanvasTest.scala └── strings ├── ParenthesesValidatorTest.scala └── WildCardMatchingTest.scala /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/cak,scala,intellij 2 | 3 | #!! ERROR: cak is undefined. Use list command to see defined gitignore types !!# 4 | 5 | ### Scala ### 6 | *.class 7 | *.log 8 | 9 | # sbt specific 10 | .cache 11 | .history 12 | .lib/ 13 | dist/* 14 | target/ 15 | lib_managed/ 16 | src_managed/ 17 | project/boot/ 18 | project/plugins/project/ 19 | 20 | # Scala-IDE specific 21 | .scala_dependencies 22 | .worksheet 23 | # Build Server Protocol 24 | .bsp/ 25 | 26 | ### Intellij ### 27 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio 28 | 29 | *.iml 30 | 31 | ## Directory-based project format: 32 | .idea/ 33 | # if you remove the above rule, at least ignore the following: 34 | 35 | # User-specific stuff: 36 | # .idea/workspace.xml 37 | # .idea/tasks.xml 38 | # .idea/dictionaries 39 | 40 | # Sensitive or high-churn files: 41 | # .idea/dataSources.ids 42 | # .idea/dataSources.xml 43 | # .idea/sqlDataSources.xml 44 | # .idea/dynamic.xml 45 | # .idea/uiDesigner.xml 46 | 47 | # Gradle: 48 | # .idea/gradle.xml 49 | # .idea/libraries 50 | 51 | # Mongo Explorer plugin: 52 | # .idea/mongoSettings.xml 53 | 54 | ## File-based project format: 55 | *.ipr 56 | *.iws 57 | 58 | ## Plugin-specific files: 59 | 60 | # IntelliJ 61 | /out/ 62 | 63 | # mpeltonen/sbt-idea plugin 64 | .idea_modules/ 65 | 66 | # JIRA plugin 67 | atlassian-ide-plugin.xml 68 | 69 | # Crashlytics plugin (for Android Studio and IntelliJ) 70 | com_crashlytics_export_strings.xml 71 | crashlytics.properties 72 | crashlytics-build.properties 73 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | scala: 3 | - 2.11.7 4 | script: "sbt clean coverage test" 5 | after_success: "sbt coveralls" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/maximn/coding-interview-questions-scala.svg?branch=master)](https://travis-ci.org/maximn/coding-interview-questions-scala) 2 | [![Coverage Status](https://coveralls.io/repos/maximn/coding-interview-questions-scala/badge.svg?branch=master&service=github)](https://coveralls.io/github/maximn/coding-interview-questions-scala?branch=master) 3 | 4 | # coding-interview-questions 5 | ## Coding interview questions with solutions and tests (Scala) 6 | 7 | 8 | ## Questions - 9 | * [Fibonacci](https://github.com/maximn/coding-interview-questions-scala/tree/master/src/main/scala/org/questions/fibonacci) 10 | * [Bucket Fill](https://github.com/maximn/coding-interview-questions-scala/tree/master/src/main/scala/org/questions/fill) 11 | * [Arrays](https://github.com/maximn/coding-interview-questions-scala/tree/master/src/main/scala/org/questions/arrays) 12 | * [Strings](https://github.com/maximn/coding-interview-questions-scala/tree/master/src/main/scala/org/questions/strings) 13 | * [Tax Calculator](https://github.com/maximn/TaxCalculator) 14 | -------------------------------------------------------------------------------- /build.sbt: -------------------------------------------------------------------------------- 1 | name := "coding-interview-questions" 2 | 3 | version := "1.0" 4 | 5 | scalaVersion := "2.13.12" 6 | 7 | libraryDependencies ++= Seq( 8 | "org.specs2" %% "specs2-core" % "4.20.5" % "test", 9 | "org.specs2" %% "specs2-scalacheck" % "4.20.5" % "test" 10 | ) 11 | 12 | scalacOptions in Test ++= Seq("-Yrangepos") -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.9.9 -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | logLevel := Level.Warn 2 | 3 | resolvers += Classpaths.sbtPluginReleases 4 | 5 | addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.9") 6 | 7 | addSbtPlugin("org.scoverage" % "sbt-coveralls" % "1.3.11") 8 | 9 | 10 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/arrays/ArrayMaxSumNonConsecutive.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import scala.annotation.tailrec 4 | 5 | /** 6 | * @author maximn 7 | * @since 28-Oct-2015 8 | */ 9 | trait ArrayMaxSumNonConsecutive { 10 | def maxSum(numbers: Seq[Int]): Int 11 | } 12 | 13 | class Recursive extends ArrayMaxSumNonConsecutive { 14 | def maxSum(numbers: Seq[Int]): Int = numbers match { 15 | case Nil => 0 16 | case Seq(n) => n 17 | case Seq(a, b) => Math.max(a, b) 18 | case head :: tail => 19 | val currentAndSkipOne = head + maxSum(tail.tail) 20 | val skipCurrent = maxSum(tail) 21 | Math.max(currentAndSkipOne, skipCurrent) 22 | } 23 | } 24 | 25 | class DynamicProgramming extends ArrayMaxSumNonConsecutive { 26 | override def maxSum(numbers: Seq[Int]): Int = { 27 | if (numbers.isEmpty) return 0 28 | 29 | var inclusive = numbers.head 30 | var exclusive = 0 31 | 32 | for (i <- 1 until numbers.length) { 33 | val newInclusive = exclusive + numbers(i) 34 | val newExclusive = inclusive 35 | inclusive = newInclusive 36 | exclusive = newExclusive 37 | } 38 | 39 | math.max(exclusive, inclusive) 40 | } 41 | } 42 | 43 | class DynamicProgrammingImmutable extends ArrayMaxSumNonConsecutive { 44 | override def maxSum(numbers: Seq[Int]): Int = { 45 | @tailrec 46 | def inner(numbers: Seq[Int], inclusive: Int, exclusive: Int): Int = numbers match { 47 | case Nil => math.max(inclusive, exclusive) 48 | case head :: tail => inner(numbers.tail, numbers.head + exclusive, inclusive) 49 | } 50 | 51 | if (numbers.nonEmpty) 52 | inner(numbers.tail, numbers.head, 0) 53 | else 54 | 0 55 | } 56 | } -------------------------------------------------------------------------------- /src/main/scala/org/questions/arrays/LongestIncreasing.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import scala.annotation.tailrec 4 | 5 | /** 6 | * @author maximn 7 | * @since 30-Oct-2015 8 | */ 9 | trait LongestIncreasing { 10 | def findLongestIncreasing(seq: Seq[Int]): Seq[Int] 11 | } 12 | 13 | class LongestIncreasingRecursive extends LongestIncreasing { 14 | override def findLongestIncreasing(seq: Seq[Int]): Seq[Int] = { 15 | require(seq.nonEmpty) 16 | 17 | findLongestIncreasingInternal(seq) 18 | } 19 | 20 | private def findLongestIncreasingInternal(seq: Seq[Int]): Seq[Int] = seq match { 21 | case Nil => Nil 22 | case _ => 23 | val firstIncreasing = increasingSeq(seq) 24 | val otherIncreasing = findLongestIncreasingInternal(seq.drop(firstIncreasing.length)) 25 | 26 | Seq(firstIncreasing, otherIncreasing).maxBy(_.length) 27 | } 28 | 29 | @tailrec 30 | private def increasingSeq(seq: Seq[Int], res: Seq[Int] = Nil): Seq[Int] = seq match { 31 | case head :: (tail@Seq(next, _*)) => 32 | if (head < next) increasingSeq(tail, res :+ head) 33 | else res :+ head 34 | case Seq(single) => res :+ single 35 | case _ => res 36 | } 37 | } 38 | 39 | class LongestIncreasingIterative extends LongestIncreasing { 40 | def findLongestIncreasing(seq: Seq[Int]): Seq[Int] = { 41 | require(seq.nonEmpty) 42 | 43 | var localLongest = Seq[Int](seq.head) 44 | var globalLongest = Seq[Int]() 45 | def setGlobalFromLonger(): Unit = { 46 | globalLongest = Seq(localLongest, globalLongest).maxBy(_.length) 47 | } 48 | 49 | for (i <- seq.indices.drop(1)) { 50 | val prev = seq(i - 1) 51 | val current = seq(i) 52 | 53 | if (prev < current) { 54 | localLongest = localLongest :+ current 55 | } 56 | else { 57 | setGlobalFromLonger() 58 | localLongest = Seq(current) 59 | } 60 | } 61 | 62 | setGlobalFromLonger() 63 | 64 | globalLongest 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/arrays/TwoSum.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import scala.annotation.tailrec 4 | import scala.collection.immutable.HashSet 5 | 6 | /** 7 | * @author maximn 8 | * @since 30-Oct-2015 9 | */ 10 | class TwoSum { 11 | def findPairSum(seq: Seq[Int], sum: Int): Option[(Int, Int)] = { 12 | 13 | @tailrec 14 | def inner(seq: Seq[Int], hash: HashSet[Int]): Option[(Int, Int)] = seq match { 15 | case Nil => None 16 | case head :: tail => 17 | val lookingFor = sum - head 18 | if (hash.contains(lookingFor)) 19 | Some(head -> lookingFor) 20 | else inner(tail, hash + head) 21 | } 22 | 23 | inner(seq, HashSet.empty[Int]) 24 | } 25 | } -------------------------------------------------------------------------------- /src/main/scala/org/questions/arrays/readme.md: -------------------------------------------------------------------------------- 1 | # ArrayMaxSumNonConsecutive 2 | Given an array of numbers, find the highest sum of non-consecutive numbers. 3 | Example : 4 | [1, 2, 3, 4, 5] 5 | ! ! ! 6 | 1 + 3 + 5 = 9. Therefore, 9 is the answer. 7 | 8 | #TwoSum 9 | Given an array, find a pair in the array that would add up to the given sum. 10 | 11 | 12 | #LongestIncreasing 13 | Given an array of integers, find the longest increasing sub-sequence. -------------------------------------------------------------------------------- /src/main/scala/org/questions/fibonacci/Fibonacci.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fibonacci 2 | 3 | /** 4 | * @author maximn 5 | * @since 26-Oct-2015 6 | */ 7 | trait Fibonacci { 8 | def nth(n: Int): Long 9 | } 10 | 11 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/fibonacci/Iterative.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fibonacci 2 | 3 | /** 4 | * @author maximn 5 | * @since 26-Oct-2015 6 | */ 7 | class Iterative extends Fibonacci { 8 | override def nth(n: Int): Long = { 9 | require(n >= 0) 10 | 11 | var current = 0 12 | var last = 1 13 | 14 | for (i <- 0 until n) { 15 | val temp = current 16 | current = last 17 | last = current + temp 18 | } 19 | 20 | current 21 | } 22 | } -------------------------------------------------------------------------------- /src/main/scala/org/questions/fibonacci/Recursive.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fibonacci 2 | 3 | /** 4 | * @author maximn 5 | * @since 26-Oct-2015 6 | */ 7 | class Recursive extends Fibonacci { 8 | override def nth(n: Int): Long = { 9 | def loop(n: Int): Long = n match { 10 | case 0 | 1 => n 11 | case _ => nth(n - 1) + nth(n - 2) 12 | } 13 | 14 | require(n >= 0) 15 | loop(n) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/fibonacci/TailRecursion.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fibonacci 2 | 3 | import scala.annotation.tailrec 4 | 5 | /** 6 | * @author maximn 7 | * @since 26-Oct-2015 8 | */ 9 | class TailRecursion extends Fibonacci { 10 | override def nth(n: Int): Long = { 11 | @tailrec 12 | def loop(n: Int, current: Int, temp: Int): Int = n match { 13 | case 0 => current 14 | case _ => loop(n - 1, temp, current + temp) 15 | } 16 | require(n >= 0) 17 | loop(n, 0, 1) 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/fibonacci/readme.md: -------------------------------------------------------------------------------- 1 | https://en.wikipedia.org/wiki/Fibonacci_number (0, 1, 1, 2, 3, 5, 8, 13, ...) 2 | 3 | Write the code that for a number `n` will return the nth number in the fibonacci sequence. 4 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/fill/Canvas.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fill 2 | 3 | /** 4 | * @author maximn 5 | * @since 27-Oct-2015 6 | */ 7 | trait Canvas { 8 | def getColor(x: Int, y: Int): Char 9 | 10 | def setColor(x: Int, y: Int, color: Char) 11 | 12 | def getSize: (Int, Int) 13 | } 14 | 15 | 16 | class CharsCanvas(canvas: Array[Array[Char]] = Array.fill[Char](5, 5)('.')) extends Canvas { 17 | require(canvas.length > 0) 18 | require(canvas.head.length > 0) 19 | 20 | override def getColor(x: Int, y: Int): Char = canvas(x)(y) 21 | 22 | override def setColor(x: Int, y: Int, color: Char): Unit = canvas(x)(y) = color 23 | 24 | override def getSize: (Int, Int) = (canvas.length, canvas.head.length) 25 | } -------------------------------------------------------------------------------- /src/main/scala/org/questions/fill/DrawUtils.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fill 2 | 3 | /** 4 | * @author maximn 5 | * @since 27-Oct-2015 6 | */ 7 | class DrawUtils(canvas: Canvas) { 8 | def fill(x: Int, y: Int, color: Char): Unit = { 9 | if (!isInCanvas(x, y)) throw new IndexOutOfBoundsException 10 | 11 | val initialColor = canvas.getColor(x, y) 12 | 13 | fillInternal(x, y, color, initialColor) 14 | } 15 | 16 | private def fillInternal(x: Int, y: Int, newColor: Char, initialColor: Char): Unit = { 17 | def shouldColor = canvas.getColor(x, y) == initialColor 18 | if (isInCanvas(x, y) && shouldColor) { 19 | canvas.setColor(x, y, newColor) 20 | 21 | Seq((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)) foreach { case (i, j) => 22 | fillInternal(i, j, newColor, initialColor) 23 | } 24 | } 25 | } 26 | 27 | private def isInCanvas(x: Int, y: Int): Boolean = 28 | (x >= 0) && 29 | (y >= 0) && 30 | (x < canvas.getSize._1) && 31 | (y < canvas.getSize._2) 32 | } -------------------------------------------------------------------------------- /src/main/scala/org/questions/fill/readme.md: -------------------------------------------------------------------------------- 1 | You need to implement the `fill` method of a paint application. 2 | ``` Scala 3 | def fill(x: Int, y: Int, color: Char): Unit 4 | ``` 5 | You start in a given point (x, y) in a grid of size (m, n) and should fill the smallest closed shape surrounding. 6 | 7 | * You have access to the canvas from withing your function. 8 | * The coordinate (0, 0) is on the Left/Top 9 | 10 | ``` Scala 11 | trait Canvas { 12 | def getColor(x: Int, y: Int): Char 13 | def setColor(x: Int, y: Int, color: Char) 14 | def getSize: (Int, Int) 15 | } 16 | ``` 17 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/strings/ParenthesesValidator.scala: -------------------------------------------------------------------------------- 1 | package org.questions.strings 2 | 3 | /** 4 | * @author maximn 5 | * @since 14-Nov-2015 6 | */ 7 | class ParenthesesValidator { 8 | def validate(str: String): Boolean = 9 | validateCharSeq(str.toList, 0) 10 | 11 | private def validateCharSeq(str: Seq[Char], count: Int): Boolean = 12 | if (count < 0) { 13 | false 14 | } 15 | else str match { 16 | case Nil => count == 0 17 | case head :: tail if head == '(' => validateCharSeq(tail, count + 1) 18 | case head :: tail if head == ')' => validateCharSeq(tail, count - 1) 19 | case _ :: tail => validateCharSeq(tail, count) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/strings/WildCardMatching.scala: -------------------------------------------------------------------------------- 1 | package org.questions.strings 2 | 3 | /** 4 | * @author maximn 5 | * @since 14-Nov-2015 6 | */ 7 | class WildCardMatching { 8 | private val matchOnce = '?' 9 | private val matchZeroOrMany = '*' 10 | 11 | def isMatching(str: String, pattern: String): Boolean = 12 | isMatchingSeq(str.toList, pattern.toList) 13 | 14 | private def isMatchingSeq(str: Seq[Char], pattern: Seq[Char]): Boolean = { 15 | (str, pattern) match { 16 | case (Nil, Nil) => true 17 | case (sHead :: sTail, pHead :: pTail) if sHead == pHead || pHead == matchOnce => 18 | isMatchingSeq(sTail, pTail) 19 | case (_ :: sTail, pHead :: pTail) if pHead == matchZeroOrMany => 20 | isMatchingSeq(sTail, pTail) || isMatchingSeq(sTail, pattern) || isMatchingSeq(str, pTail) 21 | case _ => false 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/scala/org/questions/strings/readme.md: -------------------------------------------------------------------------------- 1 | # WildCardMatching 2 | Implement wildcard pattern matching for '?' (Exactly one) and '*' (Zero/One/Many) 3 | Do not use regex. 4 | 5 | # ParenthesesValidator 6 | Given a string make sure that parentheses '(', ')' are opened/closed in the correct order 7 | -------------------------------------------------------------------------------- /src/test/scala/org/questions/FibonacciTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions 2 | 3 | import org.questions.fibonacci.{Fibonacci, Iterative, Recursive, TailRecursion} 4 | import org.scalacheck.Gen 5 | import org.specs2.ScalaCheck 6 | import org.specs2.mutable.Specification 7 | 8 | import scala.concurrent.duration.Duration 9 | import scala.concurrent.{Await, Future} 10 | 11 | /** 12 | * @author maximn 13 | * @since 26-Oct-2015 14 | */ 15 | trait FibonacciTest extends Specification with FibonacciProperty { 16 | val fib: Fibonacci 17 | 18 | "negative input" should { 19 | "be invalid" in { 20 | fib.nth(-1) must throwA[IllegalArgumentException] 21 | } 22 | } 23 | 24 | "0th" should { 25 | "be 0" in { 26 | fib.nth(0) must be_===(0) 27 | } 28 | } 29 | 30 | "1st" should { 31 | "be 1" in { 32 | fib.nth(1) must be_===(1) 33 | } 34 | } 35 | 36 | "2nd" should { 37 | "be 1" in { 38 | fib.nth(2) must be_===(1) 39 | } 40 | } 41 | } 42 | 43 | trait BigN { 44 | self: FibonacciTest => 45 | 46 | import scala.concurrent.ExecutionContext.Implicits.global 47 | 48 | "big N" should { 49 | "be computed in sub seconds" in { 50 | val calcBigN = Future.apply { 51 | fib.nth(100) 52 | } 53 | 54 | Await.ready(calcBigN, Duration("1 second")).isCompleted must beTrue 55 | } 56 | } 57 | } 58 | 59 | trait FibonacciProperty extends ScalaCheck { 60 | self: FibonacciTest => 61 | 62 | val smallInteger = Gen.choose[Int](2,30) 63 | 64 | "fib(n)" should { 65 | "be equal to the sum of the results of last 2 elements" >> prop { n: Int => 66 | fib.nth(n) must be_===(fib.nth(n - 1) + fib.nth(n - 2)) 67 | }.setGen(smallInteger) 68 | } 69 | } 70 | 71 | class RecursiveTest extends FibonacciTest { 72 | override val fib = new Recursive 73 | } 74 | 75 | class IterativeTest extends FibonacciTest with BigN { 76 | override val fib = new Iterative 77 | } 78 | 79 | class TailRecursionTest extends FibonacciTest with BigN { 80 | override val fib: Fibonacci = new TailRecursion 81 | } 82 | -------------------------------------------------------------------------------- /src/test/scala/org/questions/arrays/ArrayMaxSumNonConsecutiveTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import org.specs2.mutable.Specification 4 | 5 | 6 | /** 7 | * @author maximn 8 | * @since 28-Oct-2015 9 | */ 10 | trait ArrayMaxSumNonConsecutiveTest extends Specification { 11 | 12 | val accumulator: ArrayMaxSumNonConsecutive 13 | 14 | "maxSum" should { 15 | "be 0 for empty seq" in { 16 | accumulator.maxSum(Nil) must be_===(0) 17 | } 18 | 19 | "be the single number for a single item seq" in { 20 | accumulator.maxSum(Seq(1)) must be_===(1) 21 | } 22 | 23 | "be the Max of 2 items" in { 24 | accumulator.maxSum(Seq(1, 2)) must be_===(2) 25 | } 26 | 27 | "be the Max Sum of non consecutive numbers" in { 28 | accumulator.maxSum(Seq(1, 2, 3, 4, 5)) must be_===(9) 29 | } 30 | } 31 | } 32 | 33 | class RecursiveTest extends ArrayMaxSumNonConsecutiveTest { 34 | override val accumulator = new Recursive 35 | } 36 | 37 | class DynamicProgrammingTest extends ArrayMaxSumNonConsecutiveTest { 38 | override val accumulator = new DynamicProgramming 39 | } 40 | 41 | class DynamicProgrammingImmutableTest extends ArrayMaxSumNonConsecutiveTest { 42 | override val accumulator = new DynamicProgrammingImmutable 43 | } -------------------------------------------------------------------------------- /src/test/scala/org/questions/arrays/LongestIncreasingTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import org.specs2.mutable.Specification 4 | 5 | /** 6 | * @author maximn 7 | * @since 30-Oct-2015 8 | */ 9 | trait LongestIncreasingTest extends Specification { 10 | val finder: LongestIncreasing 11 | 12 | "empty seq" should { 13 | "throw argument exception" in { 14 | finder.findLongestIncreasing(Nil) must throwA[IllegalArgumentException] 15 | } 16 | } 17 | 18 | "single item" should { 19 | "return a seq with that item" in { 20 | finder.findLongestIncreasing(Seq(1)) must be_===(Seq(1)) 21 | } 22 | } 23 | 24 | "all increasing seq" should { 25 | "return the seq" in { 26 | finder.findLongestIncreasing(Seq(1, 2, 3, 4)) must be_===(Seq(1, 2, 3, 4)) 27 | } 28 | } 29 | 30 | "increasing starts not in the beginning" should { 31 | "return the increasing seq" in { 32 | finder.findLongestIncreasing(Seq(8, 1, 2, 3)) must be_===(Seq(1, 2, 3)) 33 | } 34 | } 35 | 36 | "findLongestIncreasing" should { 37 | "return the longest increasing seq" in { 38 | finder.findLongestIncreasing(Seq(1, 2, 0, 0, 3, 0, 4, 5, 6, 5, 2, 3)) must be_===(Seq(0, 4, 5, 6)) 39 | } 40 | } 41 | } 42 | 43 | class LongestIncreasingRecursiveTest extends LongestIncreasingTest { 44 | override val finder = new LongestIncreasingRecursive 45 | } 46 | 47 | class LongestIncreasingIterativeTest extends LongestIncreasingTest { 48 | override val finder = new LongestIncreasingIterative 49 | } 50 | -------------------------------------------------------------------------------- /src/test/scala/org/questions/arrays/TwoSumTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.arrays 2 | 3 | import org.specs2.matcher.Matcher 4 | import org.specs2.mutable.Specification 5 | import org.specs2.specification.Scope 6 | 7 | /** 8 | * @author maximn 9 | * @since 30-Oct-2015 10 | */ 11 | class TwoSumTest extends Specification { 12 | 13 | class Context extends Scope { 14 | val arrayUtils = new TwoSum 15 | 16 | def sumTo(sum: Int): Matcher[(Int, Int)] = (_: (Int, Int)) match { 17 | case (a, b) => a + b must be_===(sum) 18 | } 19 | } 20 | 21 | "under 2 elements in seq" should { 22 | "be none" in new Context { 23 | arrayUtils.findPairSum(Seq(1), 8) must beNone 24 | } 25 | } 26 | 27 | "two elements that sum" should { 28 | "return these elements" in new Context { 29 | arrayUtils.findPairSum(Seq(2, 3), 5) must beSome(sumTo(5)) 30 | } 31 | } 32 | 33 | "two elements that doesn't sum" should { 34 | "return these none" in new Context { 35 | arrayUtils.findPairSum(Seq(2, 3), 4) must beNone 36 | } 37 | } 38 | 39 | "more elements that sum" should { 40 | "return the sum" in new Context { 41 | arrayUtils.findPairSum(Seq(1, 2, 3), 5) must beSome(sumTo(5)) 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/test/scala/org/questions/fill/CanvasTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.fill 2 | 3 | import org.specs2.mutable.Specification 4 | import org.specs2.specification.Scope 5 | 6 | /** 7 | * @author maximn 8 | * @since 27-Oct-2015 9 | */ 10 | class CanvasTest extends Specification { 11 | 12 | class Context extends Scope { 13 | private val sample = 14 | """............ 15 | |.*******.... 16 | |.*....***... 17 | |.**.....*... 18 | |..*....**... 19 | |...*****....""".stripMargin 20 | 21 | private def toCharsCanvas(s: String) = 22 | new CharsCanvas(s.split("\n").map(_.toCharArray)) 23 | 24 | val canvas = toCharsCanvas(sample) 25 | val drawUtils = new DrawUtils(canvas) 26 | 27 | def >(canvas: Canvas) = { 28 | val (rows, cols) = canvas.getSize 29 | 30 | for {r <- 0 until rows} { 31 | for {c <- 0 until cols} { 32 | Predef.print(canvas.getColor(r, c)) 33 | } 34 | println() 35 | } 36 | } 37 | } 38 | 39 | Seq((1, 100), (100, 1), (-1, 1), (1, -1)) foreach { case (x, y) => 40 | "outside of the canvas" should { 41 | "result in error" in new Context { 42 | drawUtils.fill(x, y, 'X') must throwA[IndexOutOfBoundsException] 43 | } 44 | } 45 | } 46 | 47 | "adjacent fields with same color" should { 48 | "be filled" in new Context { 49 | drawUtils.fill(3, 4, '#') 50 | 51 | Seq((3, 5), (3, 3), (2, 4), (4, 4)) foreach { case (x, y) => 52 | canvas.getColor(x, y) must be_===('#') 53 | } 54 | } 55 | } 56 | 57 | "adjacent fields with different color" should { 58 | "stay with previous color" in new Context { 59 | drawUtils.fill(0, 1, '#') 60 | canvas.getColor(1, 1) must be_===('*') 61 | } 62 | } 63 | 64 | "selected field" should { 65 | "be colored" in new Context { 66 | drawUtils.fill(0, 0, '#') 67 | canvas.getColor(0, 0) must be_===('#') 68 | } 69 | } 70 | 71 | "far fields that in same shape" should { 72 | "be colored" in new Context { 73 | drawUtils.fill(0, 0, '#') 74 | canvas.getColor(5, 11) must be_===('#') 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /src/test/scala/org/questions/strings/ParenthesesValidatorTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.strings 2 | 3 | import org.specs2.mutable.Specification 4 | 5 | /** 6 | * @author maximn 7 | * @since 14-Nov-2015 8 | */ 9 | class ParenthesesValidatorTest extends Specification { 10 | val validator = new ParenthesesValidator 11 | 12 | "empty parentheses" should { 13 | "be valid" in { 14 | validator.validate("(abc)") must beTrue 15 | } 16 | } 17 | 18 | "no parentheses" should { 19 | "be valid" in { 20 | validator.validate("abc") must beTrue 21 | } 22 | } 23 | 24 | "unclosed" should { 25 | "be invalid" in { 26 | validator.validate("((abc)") must beFalse 27 | } 28 | } 29 | 30 | "unopened" should { 31 | "be invalid" in { 32 | validator.validate("(abc))") must beFalse 33 | } 34 | 35 | "be invalid in beginning" in { 36 | validator.validate(")abc(") must beFalse 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/test/scala/org/questions/strings/WildCardMatchingTest.scala: -------------------------------------------------------------------------------- 1 | package org.questions.strings 2 | 3 | import org.specs2.mutable.Specification 4 | 5 | /** 6 | * @author maximn 7 | * @since 14-Nov-2015 8 | */ 9 | class WildCardMatchingTest extends Specification { 10 | val matcher = new WildCardMatching 11 | 12 | 13 | "same string" should { 14 | "be matching" in { 15 | val string = "abc" 16 | matcher.isMatching(string, string) must beTrue 17 | } 18 | } 19 | 20 | "different string" should { 21 | "not match" in { 22 | matcher.isMatching("ab", "bc") must beFalse 23 | } 24 | } 25 | 26 | "question mark" should { 27 | "allow to skip one char" in { 28 | matcher.isMatching("abc", "a?c") must beTrue 29 | } 30 | } 31 | 32 | "star" should { 33 | "replace many chars" in { 34 | matcher.isMatching("abcd", "a*d") must beTrue 35 | } 36 | 37 | "replace zero chars" in { 38 | matcher.isMatching("abc", "ab*c") must beTrue 39 | } 40 | 41 | "replace one char" in { 42 | matcher.isMatching("abc", "a*c") must beTrue 43 | } 44 | 45 | "match if star is in the end" in { 46 | matcher.isMatching("abc", "a*") must beTrue 47 | } 48 | } 49 | } 50 | --------------------------------------------------------------------------------