diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1218db4 --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ +build-docker: + docker build -f distribution/docker/Dockerfile --build-arg JAR_FILE=build/libs/\*.jar -t lindar/bingoticketgenerator-apalfi:0.0.1-SNAPSHOT . + +build-gradle: + ./gradlew clean build + +build: build-gradle build-docker + +run-docker: + docker run -p 8080:8080 lindar/bingoticketgenerator-apalfi:0.0.1-SNAPSHOT + +boot-run: + ./gradlew bootRun + +run-tests: + ./gradlew test --tests "com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator*" + +run-perf-tests: + ./gradlew test --tests 'com.attilapalfi.lindar.bingoticketgenerator.performancetest*' diff --git a/README.md b/README.md index 7855e05..a3e0b9b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,56 @@ + +## System Requirements +- Java 17, gradle +- Docker + +## Build & Run +Use the Makefile to execute build & run commands. + +To build with gradle and docker: +```shell +make build +``` + +To run the docker container: +```shell +make run-docker +``` +If the container started, the ticket generator endpoint is available at: + +### [http://localhost:8080/bingo/newStrips](http://localhost:8080/bingo/newStrips) + +To run tests or performance tests: +```shell +make run-tests +make run-perf-tests +``` + +## Implementation Details +- `-1` means `Blank` space in the ticket +- the core part of the algorithm is in `AbstractTicketGenerator` + - it iterates through the spaces of the tickets row by row and based on a set of rules it places the blanks and numbers +- time complexity of the algorithm is `O(n)` with some amortized time, where `n` is the total number of spaces in the 6 tickets + - the algorithm is hard to scale though. it was specifically implemented to generate 3x9 tickets in batches of 6 +- array lists are initialized in the `ArrayBasedTicketGenerator` to keep track of the state of the ticket generator + - these array lists are maybe not optimal: removing an element has `O(n)` time complexity + - it is possible to create another subclass for `AbstractTicketGenerator` which uses another approach + - e.g. instead of array lists, shuffled linked lists. removing from LL: `O(1)`, shuffling during init: `O(nlogn)` + - altough these are very small array lists: `n` is usually smaller than 20 +- an error checking is part of the algorithm, because in very rare cases an invalid ticket is generated. +As soon as it's detected, the algorithm drops it and starts creating a new one. + - luckily this does not have a performance impact because it's so rare + +## Performance +On my machine the performance test executed with these results: + +`Generated 10.000 strips in 487 ms.` + +And with 16 threads: + +`Generated 100.000 strips in parallel in 1602 ms.` + +------ +Original content: # Ticket Generator Challenge A small challenge that involves building a [Bingo 90](https://en.wikipedia.org/wiki/Bingo_(United_Kingdom)) ticket generator. @@ -19,3 +72,4 @@ A small challenge that involves building a [Bingo 90](https://en.wikipedia.org/w Try to also think about the performance aspects of your solution. How long does it take to generate 10k strips? The recommended time is less than 1s (with a lightweight random implementation) + diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..929a851 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,35 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + id("org.springframework.boot") version "2.7.1" + id("io.spring.dependency-management") version "1.0.11.RELEASE" + kotlin("jvm") version "1.6.21" + kotlin("plugin.spring") version "1.6.21" +} + +group = "com.attilapalfi.lindar" +version = "0.0.1-SNAPSHOT" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + testImplementation("org.springframework.boot:spring-boot-starter-test") +} + +tasks.withType { + kotlinOptions { + freeCompilerArgs = listOf("-Xjsr305=strict") + jvmTarget = "17" + } +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/distribution/docker/Dockerfile b/distribution/docker/Dockerfile new file mode 100644 index 0000000..ec52d9e --- /dev/null +++ b/distribution/docker/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:17-alpine +ARG JAR_FILE=target/*.jar +COPY ${JAR_FILE} app.jar +ENTRYPOINT ["java","-jar","/app.jar"] \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..41d9927 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..00e33ed --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..1283238 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "bingo-ticket-generator" diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/BingoTicketGeneratorApplication.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/BingoTicketGeneratorApplication.kt new file mode 100644 index 0000000..c0313dc --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/BingoTicketGeneratorApplication.kt @@ -0,0 +1,11 @@ +package com.attilapalfi.lindar.bingoticketgenerator + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class BingoTicketGeneratorApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/DeterministicRandomProvider.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/DeterministicRandomProvider.kt new file mode 100644 index 0000000..aadd29d --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/DeterministicRandomProvider.kt @@ -0,0 +1,10 @@ +package com.attilapalfi.lindar.bingoticketgenerator.random + +import org.springframework.stereotype.Component + +@Component +class DeterministicRandomProvider : RandomProvider { + override fun nextInt(until: Int): Int { + return 0 + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/RandomProvider.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/RandomProvider.kt new file mode 100644 index 0000000..4af43b1 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/RandomProvider.kt @@ -0,0 +1,5 @@ +package com.attilapalfi.lindar.bingoticketgenerator.random + +interface RandomProvider { + fun nextInt(until: Int): Int +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/SimpleRandomProvider.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/SimpleRandomProvider.kt new file mode 100644 index 0000000..495b0c9 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/random/SimpleRandomProvider.kt @@ -0,0 +1,18 @@ +package com.attilapalfi.lindar.bingoticketgenerator.random + +import org.springframework.stereotype.Component +import kotlin.random.Random + +@Component +class SimpleRandomProvider : RandomProvider { + + private val random = Random(System.currentTimeMillis()) + + override fun nextInt(until: Int): Int { + return if (until == 0) { + 0 + } else { + random.nextInt(until) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/AbstractTicketGenerator.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/AbstractTicketGenerator.kt new file mode 100644 index 0000000..9aafa70 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/AbstractTicketGenerator.kt @@ -0,0 +1,196 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +import com.attilapalfi.lindar.bingoticketgenerator.random.RandomProvider +import kotlin.math.min + +const val BLANK = -1 +const val TICKETS = 6 +const val ROWS = 3 +const val NUMBERS_IN_ROW = 5 +const val BLANKS_IN_ROW = 4 +const val COLUMNS = NUMBERS_IN_ROW + BLANKS_IN_ROW +const val SPACES_IN_TICKET = COLUMNS * ROWS + +const val NUMBERS_IN_FIRST_COLUMN = 9 +const val NUMBERS_IN_MIDDLE_COLUMNS = 10 +const val NUMBERS_IN_LAST_COLUMN = 11 +const val TOTAL_ROWS_IN_STRIP_OF_SIX = 18 + +sealed class AbstractTicketGenerator(protected val randomProvider: RandomProvider) : TicketGenerator { + protected lateinit var sixTickets: SixTickets + protected lateinit var remainingBlanksInColumn: MutableMap + private lateinit var remainingNumbersInRow: MutableMap + + + override fun generateTickets(): SixTickets { + initNewStripOfSix() + loop@ for (ticket in 0 until TICKETS) { + if (sixTickets.invalid) break@loop + for (row in 0 until ROWS) { + if (sixTickets.invalid) break@loop + fillRow(ticket, row) + } + } + return returnOrRegenerateIfInvalid() + } + + private fun fillRow(ticket: Int, row: Int) { + val mustBlankSpaces = HashSet() + val mustNumberSpaces = HashSet() + val columnIndices = Array(COLUMNS) { it }.toMutableList().shuffled() + fillWithMandatoryBlanksAndNumbers(columnIndices, ticket, row, mustBlankSpaces, mustNumberSpaces) + fillTheRestWithBlanksAndNumbers(columnIndices, mustBlankSpaces, mustNumberSpaces, ticket, row) + setInvalidIfNeeded(ticket, row) + } + + private fun fillWithMandatoryBlanksAndNumbers( + columnIndices: List, + ticket: Int, + row: Int, + mustBlankSpaces: HashSet, + mustNumberSpaces: HashSet + ) { + var columnIterationsLeft = 8 + columnIndices.forEachIndexed { columnIterator, column -> + if (canBeBlank(ticket, row, column) && mustBeBlank( + ticket, + row, + column, + columnIterator, + columnIndices + ) + ) { + mustBlankSpaces.add(column) + addBlank(ticket, row, column) + } else if (mustBeNumber(ticket, row, column, columnIterationsLeft)) { + mustNumberSpaces.add(column) + addNumber(ticket, row, column) + } + columnIterationsLeft-- + } + } + + private fun fillTheRestWithBlanksAndNumbers( + columnIndices: List, + mustBlankSpaces: HashSet, + mustNumberSpaces: HashSet, + ticket: Int, + row: Int + ) { + var columnIterationsLeft = 8 + columnIndices.forEach { column -> + if (!mustBlankSpaces.contains(column) && !mustNumberSpaces.contains(column)) { + if (canBeBlank(ticket, row, column) && isBlank(ticket, row, column)) { + addBlank(ticket, row, column) + } else { + addNumber(ticket, row, column) + } + } + columnIterationsLeft-- + } + } + + private fun setInvalidIfNeeded(ticket: Int, row: Int) { + if (isRowInvalidValid(ticket, row)) { + sixTickets.invalid = true + } + } + + private fun isRowInvalidValid(ticket: Int, row: Int) = + sixTickets.tickets[ticket].getRow(row).count { it > 0 } != NUMBERS_IN_ROW + + private fun returnOrRegenerateIfInvalid(): SixTickets { + return if (sixTickets.invalid) { + generateTickets() + } else { + sixTickets + } + } + + abstract fun mustBeBlank( + ticket: Int, + row: Int, + column: Int, + columnIterator: Int, + columnIndices: List + ): Boolean + + protected abstract fun doInit() + + protected abstract fun nextNumber(ticket: Int, row: Int, column: Int): Int + + protected abstract fun mustBeNumber(ticket: Int, row: Int, column: Int, columnIterationsLeft: Int): Boolean + + protected abstract fun canBeBlank(ticket: Int, row: Int, column: Int): Boolean + + protected abstract fun isBlank(ticket: Int, row: Int, column: Int): Boolean + + protected fun remainingTotalRows(ticket: Int, row: Int): Int { + return ((TICKETS - (ticket + 1)) * ROWS) + (ROWS - row) + } + + protected fun getRemainingNumbersInRow(ticket: Int, row: Int): Int { + return remainingNumbersInRow[ticket * ROWS + row]!! + } + + protected fun decrementRemainingNumbersInRow(ticket: Int, row: Int) { + remainingNumbersInRow[ticket * ROWS + row] = remainingNumbersInRow[ticket * ROWS + row]!! - 1 + } + + protected fun maxPossibleBlanksInColumn(ticket: Int, row: Int, column: Int): Int { + val remainingFullTickets = TICKETS - (ticket + 1) + var possibleBlanks = remainingFullTickets * 2 + var possibleBlanksInTicketColumn = 0 + for (i in row until ROWS) { + if (sixTickets.tickets[ticket].canBeBlankByColumn(i, column)) { + possibleBlanksInTicketColumn++ + } + } + possibleBlanks += min(possibleBlanksInTicketColumn, 2) + return possibleBlanks + } + + protected fun maxPossibleBlanksInRow( + ticket: Int, + row: Int, + columnIterator: Int, + columnIndices: List + ): Int { + var possibleBlanks = 0 + for (i in columnIterator until columnIndices.size) { + if (canBeBlank(ticket, row, columnIndices[i])) { + possibleBlanks++ + } + } + return possibleBlanks + } + + private fun initNewStripOfSix() { + sixTickets = SixTickets() + remainingBlanksInColumn = hashMapOf( + Pair(0, 9), + Pair(1, 8), + Pair(2, 8), + Pair(3, 8), + Pair(4, 8), + Pair(5, 8), + Pair(6, 8), + Pair(7, 8), + Pair(8, 7), + ) + remainingNumbersInRow = HashMap() + for (i in 0 until TOTAL_ROWS_IN_STRIP_OF_SIX) { + remainingNumbersInRow[i] = NUMBERS_IN_ROW + } + doInit() + } + + private fun addNumber(ticket: Int, row: Int, column: Int) { + val number = nextNumber(ticket, row, column) + sixTickets.tickets[ticket].setValue(row, column, number) + } + + private fun addBlank(ticket: Int, row: Int, column: Int) { + sixTickets.tickets[ticket].setValue(row, column, BLANK) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGenerator.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGenerator.kt new file mode 100644 index 0000000..da6b81a --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGenerator.kt @@ -0,0 +1,122 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +import com.attilapalfi.lindar.bingoticketgenerator.random.RandomProvider +import java.util.stream.IntStream + +class ArrayBasedTicketGenerator(randomProvider: RandomProvider) : AbstractTicketGenerator(randomProvider) { + private lateinit var numberArrays: ArrayList> + private lateinit var isBlankArrays: ArrayList>> + + override fun doInit() { + numberArrays = copyNumbersAsArrayList() + isBlankArrays = ArrayList(TICKETS) + IntStream.range(0, TICKETS).forEach { + isBlankArrays.add(copyBlanksAsArrayList()) + } + } + + override fun nextNumber(ticket: Int, row: Int, column: Int): Int { + if (numberArrays[column].isEmpty()) { + // this should not happen + sixTickets.invalid = true + return BLANK + } + decrementRemainingNumbersInRow(ticket, row) + val randomIndex = randomProvider.nextInt(numberArrays[column].size) + return numberArrays[column].removeAt(randomIndex) + } + + override fun mustBeNumber(ticket: Int, row: Int, column: Int, columnIterationsLeft: Int): Boolean { + if (getRemainingNumbersInRow(ticket, row) == columnIterationsLeft + 1) { + return true + } + val remainingTotalRows = remainingTotalRows(ticket, row) + return remainingTotalRows == numberArrays[column].size + } + + override fun mustBeBlank( + ticket: Int, + row: Int, + column: Int, + columnIterator: Int, + columnIndices: List + ): Boolean { + val mustBeBlankByRow = + remainingBlanksInRow(ticket, row) == maxPossibleBlanksInRow(ticket, row, columnIterator, columnIndices) + val mustBeBlankByColumn = remainingBlanksInColumn[column]!! == maxPossibleBlanksInColumn(ticket, row, column) + + if (mustBeBlankByRow || mustBeBlankByColumn) { + remainingBlanksInColumn[column] = remainingBlanksInColumn[column]!! - 1 + isBlankArrays[ticket][row].removeAt(0) + return true + } + + return false + } + + override fun canBeBlank(ticket: Int, row: Int, column: Int): Boolean { + val canBeBlankByColumn = sixTickets.tickets[ticket].canBeBlankByColumn(row, column) + val canBeBlankByRow = isBlankArrays[ticket][row][0] + return canBeBlankByColumn && canBeBlankByRow && remainingBlanksInColumn[column]!! > 0 + } + + override fun isBlank(ticket: Int, row: Int, column: Int): Boolean { + val randomIndex = randomProvider.nextInt(isBlankArrays[ticket][row].size) + val isBlank = isBlankArrays[ticket][row].removeAt(randomIndex) + if (isBlank) { + remainingBlanksInColumn[column] = remainingBlanksInColumn[column]!! - 1 + } + return isBlank + } + + private fun remainingBlanksInRow(ticket: Int, row: Int) = isBlankArrays[ticket][row].count { it } + + private fun copyNumbersAsArrayList(): ArrayList> { + val numberArrays = ArrayList>(numberArrayStorage.size) + numberArrayStorage.forEach { + numberArrays.add(arrayListOf(*it.copyOf().toTypedArray())) + } + return numberArrays + } + + private fun copyBlanksAsArrayList(): ArrayList> { + val isBlankArrays = ArrayList>(isBlankArrayStorage.size) + isBlankArrayStorage.forEach { + isBlankArrays.add(arrayListOf(*it.copyOf().toTypedArray())) + } + return isBlankArrays + } + + companion object { + private val numberArrayStorage: Array = Array(COLUMNS) { arrayIndex -> + if (arrayIndex == 0) { + val array = IntArray(NUMBERS_IN_FIRST_COLUMN) + for (i in 1..array.size) { + array[i - 1] = i + } + array + } else if (arrayIndex < 8) { + val array = IntArray(NUMBERS_IN_MIDDLE_COLUMNS) + for (i in array.indices) { + array[i] = 10 * arrayIndex + i + } + array + } else { + val array = IntArray(NUMBERS_IN_LAST_COLUMN) + for (i in array.indices) { + array[i] = 10 * arrayIndex + i + } + array + } + } + + private val isBlankArrayStorage: Array = Array(3) { + val array = BooleanArray(COLUMNS) + for (i in array.indices) { + array[i] = i < BLANKS_IN_ROW + } + array + } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/SixTickets.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/SixTickets.kt new file mode 100644 index 0000000..708472f --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/SixTickets.kt @@ -0,0 +1,20 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +import java.util.stream.IntStream + +class SixTickets { + val tickets: ArrayList = ArrayList(6) + var invalid: Boolean = false + + init { + IntStream.range(0, TICKETS).forEach { + tickets.add(Ticket()) + } + } + + override fun toString(): String { + val stringBuilder = StringBuilder() + tickets.forEach { stringBuilder.append(it).append("\n") } + return stringBuilder.toString() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/Ticket.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/Ticket.kt new file mode 100644 index 0000000..9d930ee --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/Ticket.kt @@ -0,0 +1,79 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +class Ticket { + + private val ticket: IntArray = IntArray(SPACES_IN_TICKET) + private val ticketValueComparator = TicketValueComparator() + + fun setValue(row: Int, column: Int, value: Int) { + if (row == 0) { + ticket[0 * COLUMNS + column] = value + } else if (row == 1) { + val array = intArrayOf(getValue(0, column), value) + val sorted = array.sortedWith(ticketValueComparator) + ticket[0 * COLUMNS + column] = sorted[0] + ticket[1 * COLUMNS + column] = sorted[1] + } else if (row == 2) { + val array = intArrayOf(getValue(0, column), getValue(1, column), value) + val sorted = array.sortedWith(ticketValueComparator) + ticket[0 * COLUMNS + column] = sorted[0] + ticket[1 * COLUMNS + column] = sorted[1] + ticket[2 * COLUMNS + column] = sorted[2] + } + } + + fun getValue(row: Int, column: Int): Int { + return ticket[row * COLUMNS + column] + } + + fun canBeBlankByColumn(row: Int, column: Int): Boolean { + val otherRow1 = (row + 1) % ROWS + val otherRow2 = (row + 2) % ROWS + return getValue(otherRow1, column) != BLANK || getValue(otherRow2, column) != BLANK + } + + fun getValues(): List { + return arrayListOf(*ticket.toTypedArray()) + } + + fun getRow(row: Int): IntArray { + return ticket.copyOfRange(row * COLUMNS, (row + 1) * COLUMNS) + } + + fun getRowsOfTicket(): List> { + val rows = ArrayList>() + for (i in 0 until SPACES_IN_TICKET) { + val rowIndex: Int = i / COLUMNS + if (i % COLUMNS == 0) { + rows.add(ArrayList()) + } + rows[rowIndex].add(ticket[i]) + } + return rows + } + + fun getColumnsOfTicket(): List> { + val columns = ArrayList>() + for (i in 0 until COLUMNS) { + columns.add(ArrayList()) + } + for (row in 0 until ROWS) { + for (column in 0 until COLUMNS) { + columns[column].add(getValue(row, column)) + } + } + return columns + } + + override fun toString(): String { + val stringBuilder = StringBuilder() + for (row in 0 until ROWS) { + for (column in 0 until COLUMNS) { + stringBuilder.append(getValue(row, column)).append(" ") + } + stringBuilder.append("\n") + } + stringBuilder.append("\n---------------------\n") + return stringBuilder.toString() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketGenerator.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketGenerator.kt new file mode 100644 index 0000000..d596a7d --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketGenerator.kt @@ -0,0 +1,5 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +sealed interface TicketGenerator { + fun generateTickets(): SixTickets +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparator.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparator.kt new file mode 100644 index 0000000..01e828e --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparator.kt @@ -0,0 +1,12 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +class TicketValueComparator : Comparator { + + override fun compare(o1: Int, o2: Int): Int { + return if (o1 == BLANK || o2 == BLANK || o1 == 0 || o2 == 0) { + 0 + } else { + o1.compareTo(o2) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/BingoController.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/BingoController.kt new file mode 100644 index 0000000..80580b6 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/BingoController.kt @@ -0,0 +1,18 @@ +package com.attilapalfi.lindar.bingoticketgenerator.web + +import org.springframework.http.ResponseEntity +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestMapping + +@Controller +@RequestMapping("bingo") +class BingoController( + private val ticketGenerator: TicketGeneratorService +) { + + @GetMapping("newStrips", produces = ["text/formatted"]) + fun generateNewStrips(): ResponseEntity { + return ResponseEntity.ok(ticketGenerator.generateStripOfSix().toString()) + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/StripsResponse.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/StripsResponse.kt new file mode 100644 index 0000000..c150d55 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/StripsResponse.kt @@ -0,0 +1,24 @@ +package com.attilapalfi.lindar.bingoticketgenerator.web + +data class StripsResponse(val tickets: List) { + override fun toString(): String { + val stringBuilder = StringBuilder() + tickets.forEach { + stringBuilder.append(it.toString()) + .append("\n-----------------------------------\n") + } + return stringBuilder.toString() + } +} + +data class TicketResponse( + val rows: List> +) { + override fun toString(): String { + val stringBuilder = StringBuilder() + rows.forEach { row -> + stringBuilder.append(row.toString()).append("\n") + } + return stringBuilder.toString() + } +} \ No newline at end of file diff --git a/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/TicketGeneratorService.kt b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/TicketGeneratorService.kt new file mode 100644 index 0000000..a02a7b0 --- /dev/null +++ b/src/main/kotlin/com/attilapalfi/lindar/bingoticketgenerator/web/TicketGeneratorService.kt @@ -0,0 +1,19 @@ +package com.attilapalfi.lindar.bingoticketgenerator.web + +import com.attilapalfi.lindar.bingoticketgenerator.random.RandomProvider +import com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator.ArrayBasedTicketGenerator +import com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator.TicketGenerator +import org.springframework.stereotype.Service + +@Service +class TicketGeneratorService(private val simpleRandomProvider: RandomProvider) { + + fun generateStripOfSix(): StripsResponse { + val ticketGenerator: TicketGenerator = ArrayBasedTicketGenerator(simpleRandomProvider) + val sixTickets = ticketGenerator.generateTickets() + + return StripsResponse( + tickets = sixTickets.tickets.map { ticket -> TicketResponse(ticket.getRowsOfTicket()) } + ) + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..2df5b15 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,4 @@ +logging: + level: + root: INFO + org.springframework.web: DEBUG diff --git a/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/performancetest/PerformanceTest.kt b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/performancetest/PerformanceTest.kt new file mode 100644 index 0000000..1740659 --- /dev/null +++ b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/performancetest/PerformanceTest.kt @@ -0,0 +1,55 @@ +package com.attilapalfi.lindar.bingoticketgenerator.performancetest + +import com.attilapalfi.lindar.bingoticketgenerator.random.SimpleRandomProvider +import com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator.ArrayBasedTicketGenerator +import org.junit.jupiter.api.Test +import java.util.concurrent.Executors +import java.util.concurrent.Future + +class PerformanceTest { + + private val randomProvider = SimpleRandomProvider() + + @Test + fun `measure time for 10_000 strip generation`() { + warmUpJvm() + + val strips = 10_000 + val startTime = System.currentTimeMillis() + for (i in 0 until strips) { + ArrayBasedTicketGenerator(randomProvider).generateTickets() + } + val executionTime = System.currentTimeMillis() - startTime + println("Generated $strips strips in $executionTime ms.") + } + + @Test + fun `measure time for 100_000 strip generation in parallel`() { + warmUpJvm() + + val strips = 100_000 + val startTime = System.currentTimeMillis() + val threads = Runtime.getRuntime().availableProcessors() + val executorService = Executors.newFixedThreadPool(threads) + val chunkSize = strips / threads + val futures = mutableListOf>() + for (i in 0 until threads) { + val future = executorService.submit { + for (j in 0..chunkSize) { + ArrayBasedTicketGenerator(randomProvider).generateTickets() + } + } + futures.add(future) + } + futures.forEach { it.get() } + executorService.shutdown() + val executionTime = System.currentTimeMillis() - startTime + println("Generated $strips strips in parallel in $executionTime ms.") + } + + private fun warmUpJvm() { + for (i in 0 until 1000) { + ArrayBasedTicketGenerator(randomProvider).generateTickets() + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGeneratorTest.kt b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGeneratorTest.kt new file mode 100644 index 0000000..a0391dd --- /dev/null +++ b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/ArrayBasedTicketGeneratorTest.kt @@ -0,0 +1,122 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +import com.attilapalfi.lindar.bingoticketgenerator.random.DeterministicRandomProvider +import com.attilapalfi.lindar.bingoticketgenerator.random.SimpleRandomProvider +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.fail + +class ArrayBasedTicketGeneratorTest { + + private lateinit var underTest: ArrayBasedTicketGenerator + + @Test + fun runAllTestsMultipleTimes() { + for (i in 0 .. 1000) { + `test with deterministic random provider`() + `test with simple random provider`() + } + } + + @Test + fun `test with deterministic random provider`() { + underTest = ArrayBasedTicketGenerator(DeterministicRandomProvider()) + + val sixTickets = underTest.generateTickets() + println(sixTickets) + + validateSixTickets(sixTickets) + } + + @Test + fun `test with simple random provider`() { + underTest = ArrayBasedTicketGenerator(SimpleRandomProvider()) + + val sixTickets = underTest.generateTickets() + println(sixTickets) + + validateSixTickets(sixTickets) + } + + private fun validateSixTickets(sixTickets: SixTickets) { + val numberSet = HashSet(90) + for (i in 1..90) { + numberSet.add(i) + } + var iterator = 0 + sixTickets.tickets.forEachIndexed { ticketIndex, ticket -> + validateRowRules(ticketIndex, ticket) + validateColumnRules(ticketIndex, ticket) + ticket.getValues().forEach { value -> + val ticketValueIndex = iterator - (ticketIndex * 27) + val rowInTicket = ticketValueIndex / 9 + val columnInTicket = ticketValueIndex - (rowInTicket * 9) + + if (value != BLANK) { + validateValueIsNotDuplicated(value, numberSet) + validateValueIsInCorrectColumn(value, columnInTicket) + } + iterator++ + } + } + } + + private fun validateRowRules(ticketIndex: Int, ticket: Ticket) { + val rows = ticket.getRowsOfTicket() + assertEquals(3, rows.size) + rows.forEachIndexed { rowIndex, row -> + val numbersInRow = row.count { it > 0 } + val blanksInRow = row.count { it < 0 } + assertEquals( + 5, + numbersInRow, + "Row '$rowIndex' in ticket '$ticketIndex' has invalid amount of numbers: '$numbersInRow'" + ) + assertEquals( + 4, + blanksInRow, + "Row '$rowIndex' in ticket '$ticketIndex' has invalid amount of blanks: '$blanksInRow'" + ) + } + } + + private fun validateColumnRules(ticketIndex: Int, ticket: Ticket) { + val columns = ticket.getColumnsOfTicket() + assertEquals(9, columns.size) + columns.forEachIndexed { columnIndex, column -> + val blanksInColumn = column.count { it < 0 } + assertTrue( + blanksInColumn < 3, + "Invalid number of blanks in column '$columnIndex' of ticket '$ticketIndex': '$blanksInColumn'" + ) + + val sortedColumn = column.toTypedArray() + sortedColumn.sortWith(TicketValueComparator()) + + assertArrayEquals( + sortedColumn, + column.toTypedArray(), + "Values in column '$columnIndex' in ticket '$ticketIndex' are not in ascending order" + ) + } + } + + private fun validateValueIsNotDuplicated(value: Int, numberSet: HashSet) { + if (!numberSet.contains(value)) { + fail("Number '$value' was duplicated in the tickets.") + } else { + numberSet.remove(value) + } + } + + private fun validateValueIsInCorrectColumn(value: Int, columnInTicket: Int) { + if (value == 90) { + assertEquals(8, columnInTicket) + } else { + if (value < columnInTicket * 10 || value >= columnInTicket * 10 + 10) { + fail("Invalid value in column '$columnInTicket': '$value'") + } + } + } +} \ No newline at end of file diff --git a/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparatorTest.kt b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparatorTest.kt new file mode 100644 index 0000000..a5e3561 --- /dev/null +++ b/src/test/kotlin/com/attilapalfi/lindar/bingoticketgenerator/ticketgenerator/TicketValueComparatorTest.kt @@ -0,0 +1,21 @@ +package com.attilapalfi.lindar.bingoticketgenerator.ticketgenerator + +import org.junit.jupiter.api.Assertions.* +import org.junit.jupiter.api.Test + +class TicketValueComparatorTest { + + private val ticketValueComparator = TicketValueComparator() + + @Test + fun testComparator() { + val input = intArrayOf(33, 31, -1) + val expected = intArrayOf(31, 33, -1) + + val result = input.sortedWith(ticketValueComparator) + + println(input.toList()) + assertArrayEquals(expected, result.toIntArray()) + } + +} \ No newline at end of file