SlideShare a Scribd company logo
Functional Sudoku
HOW TO SOLVE SUDOKU GRIDS IN SCALA
1
1 - Introduction
2
Table of content
1. Introduction
2. What is a Sudoku?
3. Brief introduction to Scala features
4. Let’s Get coding!
3
1-Introduction – Who am I?
 I’m Cesar Tron-Lozai
 I work for a Startup in London
 I love Java, Scala and Functional Programming
4
1-Introduction – What will talk about?
 How to solve Sudoku grids using Functional Idioms in Scala
 Have fun and hopefully learn something
 Disclaimers:
 I’m no Scala experts => please be tolerant if the Scala code smells
 Original idea from Anton Loss (@avloss) developed during a London Scala
Users Group in London
 It is not meant to be the fastest solution to solve a grid
 It does not solve hard grids (where backtracking is required)
5
2 – What’s Sudoku
6
2 – What’s Sudoku? - The rules
 9 x 9 grids
 Goal is to fill the whole grid
 All rows must have 1-9 once
 All columns must have 1-9 once
 All squares must have 1-9 once
Image credit: Wikipedia
7
3 – Brief introduction to Scala features
8
3 – Scala – Case Classes
 Case classes
 “regular classes which export their
constructor parameters and which
provide a recursive
decomposition mechanism via
pattern matching”
 Immutable
 Automatic constructors and
getters
sealed trait Shape
case class Circle(d: Double) extends Shape
case class Rectangle(w: Double, h: Double) extends Shape
val circle = Circle(22)
val rectangle = Rectangle(10, 20)
def shapePrint(shape: Shape) : String = shape match{
case Circle(d) => s"Circle [d=$d]"
case Rectangle(w, h) => s"Rectangle [w= $w, h=$h]"
}
9
3 – Scala – Filter operator
def filter[A](as: Vector[A])(f: A => Boolean) : Vector[A]
val l1 = Vector(1, 2, 3)
l1.filter(x => x % 2 == 0) //= Vector(2)
10
3 – Scala – Map operator
def map[A, B](as: Vector[A])(f: A=>B) : Vector[B]
val l1 = Vector(1, 2, 3)
l1.map(x => 2 * x) //= Vector(2, 4, 6)
11
3 – Scala – Flat Map operator
def flatMap[A, B](as: Vector[A])(f: A => Vector[B]) : Vector[B]
val l1 = Vector(1, 2, 3)
val l2 = l1.flatMap(x => Vector(x, x))
//l2 = Vector(1, 1, 2, 2, 3, 3)
12
3 – Scala – Grouped Operator
val row1 = Vector(1, 2, 3, 4): Vector[Int]
val row2 = Vector(5, 6, 7, 8): Vector[Int]
val row3 = Vector(9, 10, 11, 12): Vector[Int]
val row4 = Vector(13, 14, 15, 16): Vector[Int]
val matrix = Vector(row1, row2, row3, row4): Vector[Vector[Int]]
val g = matrix.grouped(2).toList
/*
g = [
[[1, 2, 3, 4],[5, 6, 7, 8]],
[[9, 10, 11, 12], [9, 10, 11, 12]]
]
*/
var rowIndex = 1
var colIndex = 0
val square = g(rowIndex)
.flatMap(row => row.grouped(2).toList(colIndex)) : Vector[Int]
/*
square = [9, 10, 13, 14]
*/
13
3 – Scala – Tuples
val tuple = (1, 2, 3)
//val tuple = Tuple3(1, 2, 3)
val e1 = tuple._1 //=1
val e2 = tuple._2 //=2
val e3 = tuple._3 //=3
14
3 – Scala – ZipWithIndex operator
val list = Vector("a", "b", "c")
val zipped = list.zipWithIndex
//zipped = Vector((a,0), (b,1), (c,2))
15
3 – Scala – Transpose Operator
 Transpose
 Transform a m x n matrix into a n
x m matrix
val row1 = Vector (1, 2) : Vector[Int]
val row2 = Vector(3, 4) : Vector[Int]
val row3 = Vector(5, 6) : Vector[Int]
val matrix = Vector(row1, row2, row3) : Vector[Vector[Int]]
val t = matrix.transpose
//t = Vector(Vector(1, 3, 5), Vector(2, 4, 6))
Example credit: Wikipedia
16
4 – Sudoku Solver
17
4 – Solver – Cell class
sealed trait Cell
case class Fixed(e: Int) extends Cell
case class Undetermined(values: List[Int]) extends Cell
A grid is modelled as: Vector[Vector[Cell]]
18
4 – Solver – Sudoku Class
case class Sudoku(grid: Vector[Vector[Cell]]) {
def isValueAllowedInRow(position: (Int, Int), value: Int): Boolean = ???
def isValueAllowedInColumn(position: (Int, Int), value: Int): Boolean = ???
def isValueAllowedInSquare(position: (Int, Int), value: Int): Boolean = ???
}
19
4 – Solver – Row logic
/**
* Returns true if the given value, at the given position, is allowed within its row.
* Logically this is true if the row doesn't already contain a Fixed cell with the given value
*
* @param position The position of the cell being checked
* @param value The value to test
* @return true if the value is allowed in that cell
*/
def isValueAllowedInRow(position: (Int, Int), value: Int): Boolean =
!grid(position._1).contains(Fixed(value))
20
4 – Solver – Column logic
/**
* Returns true if the given value, at the given position, is allowed within its column.
* Logically this is true if the column doesn't already contain a Fixed cell with the given
value
*
* @param position The position of the cell being checked
* @param value The value to test
* @return true if the value is allowed in that cell
*/
def isValueAllowedInColumn(position: (Int, Int), value: Int): Boolean = {
val t = grid.transpose
!t(position._2).contains(Fixed(value))
}
21
4 – Solver – Square logic
/**
* Returns true if the given value, at the given position, is allowed within its square.
* Logically this is true if the square doesn't already contain a Fixed cell with the given
value
*
* @param position The position of the cell being checked
* @param value The value to test
* @return true if the value is allowed in that cell
*/
def isValueAllowedInSquare(position: (Int, Int), value: Int): Boolean = {
val ci = position._1 / 3
val cj = position._2 / 3
val squareCells = grid.grouped(3).toList(ci).flatMap { row =>
row.grouped(3).toList(cj)
}
!squareCells.contains(Fixed(value))
}
22
4 – Solver – Logic wrapper
/**
* Returns true of the given value, at the given position is allowed. This methods combine
the row, column and
* square strategies
*
* @param position The position of the cell being checked
* @param value The value to test
* @return true if the value is allowed in that cell
*/
def isValueAllowed(position: (Int, Int), value: Int): Boolean =
isValueAllowedInRow(position, value) &&
isValueAllowedInColumn(position, value) &&
isValueAllowedInSquare(position, value)
23
4 – Solver – And finally
def filter(): Sudoku = {
val filtered: Vector[Vector[Cell]] = grid
.zipWithIndex
.map {case (row, rowIdx) =>
row
.zipWithIndex
.map {
case (Undetermined(values), colIdx) =>
Undetermined(values.filter(v => isValueAllowed((rowIdx, colIdx),v)))
case (x, _) => x
}
.map {
case Undetermined(values) if values.size == 1 => Fixed(values.head)
case x => x
}
}
if (filtered == grid) this
else Sudoku(filtered).filter()
}
24
References
 Code available on Github: https://github.com/cesartl/sudoku
 It contains a bit more error handling
 Tested again 100 simple Sudokus (https://qqwing.com/instructions.html)
 Thank you:
 Anton Loss (@avloss)
 Julien Truffaut (https://github.com/julien-truffaut)
25

More Related Content

What's hot

Relations and functions
Relations and functionsRelations and functions
Relations and functions
Heather Scott
 
Lecture 11 data structures and algorithms
Lecture 11 data structures and algorithmsLecture 11 data structures and algorithms
Lecture 11 data structures and algorithmsAakash deep Singhal
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
nikhilarora2211
 
Module 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation NotesModule 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation Notestoni dimella
 
Pre-Cal 20S January 20, 2009
Pre-Cal 20S January 20, 2009Pre-Cal 20S January 20, 2009
Pre-Cal 20S January 20, 2009
Darren Kuropatwa
 
Matlab algebra
Matlab algebraMatlab algebra
Matlab algebra
pramodkumar1804
 
LApreC2010-101-matrixquiz11a.4rq
LApreC2010-101-matrixquiz11a.4rqLApreC2010-101-matrixquiz11a.4rq
LApreC2010-101-matrixquiz11a.4rq
A Jorge Garcia
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functionstoni dimella
 
redes neuronais
redes neuronaisredes neuronais
redes neuronais
Roland Silvestre
 
Matlab quick quide3.4
Matlab  quick quide3.4Matlab  quick quide3.4
Matlab quick quide3.4
Mohamd Fawzi Nabulsi
 
Functions
FunctionsFunctions
Functions
Christian Costa
 
Relations & Functions
Relations & FunctionsRelations & Functions
Relations & FunctionsBitsy Griffin
 
Matlab
MatlabMatlab
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
Linked List Leetcode - Easy Collections - Interview Questions Java
Linked List Leetcode - Easy Collections - Interview Questions JavaLinked List Leetcode - Easy Collections - Interview Questions Java
Linked List Leetcode - Easy Collections - Interview Questions Java
Sunil Yadav
 
2 b queues
2 b queues2 b queues
2 b queues
Nguync91368
 
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
http://algorithmtraining.com/advanced-python-training-hyderabad/
 
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
http://algorithmtraining.com/advanced-python-training-hyderabad/
 

What's hot (20)

Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Lecture 11 data structures and algorithms
Lecture 11 data structures and algorithmsLecture 11 data structures and algorithms
Lecture 11 data structures and algorithms
 
Row major and column major in 2 d
Row major and column major in 2 dRow major and column major in 2 d
Row major and column major in 2 d
 
Module 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation NotesModule 1 Lesson 1 Remediation Notes
Module 1 Lesson 1 Remediation Notes
 
Functions & graphs
Functions & graphsFunctions & graphs
Functions & graphs
 
Pre-Cal 20S January 20, 2009
Pre-Cal 20S January 20, 2009Pre-Cal 20S January 20, 2009
Pre-Cal 20S January 20, 2009
 
Matlab algebra
Matlab algebraMatlab algebra
Matlab algebra
 
LApreC2010-101-matrixquiz11a.4rq
LApreC2010-101-matrixquiz11a.4rqLApreC2010-101-matrixquiz11a.4rq
LApreC2010-101-matrixquiz11a.4rq
 
Relations and Functions
Relations and FunctionsRelations and Functions
Relations and Functions
 
redes neuronais
redes neuronaisredes neuronais
redes neuronais
 
Matlab quick quide3.4
Matlab  quick quide3.4Matlab  quick quide3.4
Matlab quick quide3.4
 
Relations and functions
Relations and functionsRelations and functions
Relations and functions
 
Functions
FunctionsFunctions
Functions
 
Relations & Functions
Relations & FunctionsRelations & Functions
Relations & Functions
 
Matlab
MatlabMatlab
Matlab
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
Linked List Leetcode - Easy Collections - Interview Questions Java
Linked List Leetcode - Easy Collections - Interview Questions JavaLinked List Leetcode - Easy Collections - Interview Questions Java
Linked List Leetcode - Easy Collections - Interview Questions Java
 
2 b queues
2 b queues2 b queues
2 b queues
 
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
Algorithm Class is a Training Institute on C, C++, CPP, DS, JAVA, data struct...
 
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
Algorithm Class is a Training Institute on C, C++,C#, CPP, DS, JAVA, data str...
 

Viewers also liked

final presentation of sudoku solver project
final presentation of sudoku solver projectfinal presentation of sudoku solver project
final presentation of sudoku solver project
Arafat Bin Reza
 
God & Jigsaw-Puzzle
God & Jigsaw-PuzzleGod & Jigsaw-Puzzle
God & Jigsaw-Puzzle
Mohd Abbas Abdul Razak
 
Life Is A Puzzle
Life Is A PuzzleLife Is A Puzzle
Life Is A Puzzlevtsiri
 
NFL Teams Logic Puzzle Solution
NFL Teams Logic Puzzle SolutionNFL Teams Logic Puzzle Solution
NFL Teams Logic Puzzle Solution
PhactoidPhil
 
Puzzle solving pp ass
Puzzle solving pp assPuzzle solving pp ass
Puzzle solving pp ass
Anil Bachate
 
3D Logic Puzzle Explanation + Solution
3D Logic Puzzle Explanation + Solution3D Logic Puzzle Explanation + Solution
3D Logic Puzzle Explanation + Solution
PhactoidPhil
 
Math Puzzle
Math PuzzleMath Puzzle
Math Puzzle
Norielys Bonilla
 
Math type
Math typeMath type
Math typeli mei
 
MLB Teams Logic Puzzle Solution
MLB Teams Logic Puzzle SolutionMLB Teams Logic Puzzle Solution
MLB Teams Logic Puzzle Solution
PhactoidPhil
 
Recreational mathematics for MichMATYC 10 10
Recreational mathematics for MichMATYC 10 10Recreational mathematics for MichMATYC 10 10
Recreational mathematics for MichMATYC 10 10
nsattler
 
Puzzles of mathematics
Puzzles of mathematicsPuzzles of mathematics
Puzzles of mathematics
Manu Chandran
 
Recreational mathematics aditya verma xc
Recreational mathematics       aditya verma   xcRecreational mathematics       aditya verma   xc
Recreational mathematics aditya verma xcAditya Verma
 
Puzzles
PuzzlesPuzzles
Puzzles
alanjgrace
 
Easy maths riddles with answers
Easy maths riddles with answersEasy maths riddles with answers
Easy maths riddles with answerssumisulochana
 

Viewers also liked (20)

final presentation of sudoku solver project
final presentation of sudoku solver projectfinal presentation of sudoku solver project
final presentation of sudoku solver project
 
God & Jigsaw-Puzzle
God & Jigsaw-PuzzleGod & Jigsaw-Puzzle
God & Jigsaw-Puzzle
 
Life Is A Puzzle
Life Is A PuzzleLife Is A Puzzle
Life Is A Puzzle
 
NFL Teams Logic Puzzle Solution
NFL Teams Logic Puzzle SolutionNFL Teams Logic Puzzle Solution
NFL Teams Logic Puzzle Solution
 
Puzzle solving pp ass
Puzzle solving pp assPuzzle solving pp ass
Puzzle solving pp ass
 
3D Logic Puzzle Explanation + Solution
3D Logic Puzzle Explanation + Solution3D Logic Puzzle Explanation + Solution
3D Logic Puzzle Explanation + Solution
 
Math Puzzle
Math PuzzleMath Puzzle
Math Puzzle
 
Brainteaser
BrainteaserBrainteaser
Brainteaser
 
Math type
Math typeMath type
Math type
 
10 Puzzles Brief (with solutions)
10 Puzzles Brief (with solutions)10 Puzzles Brief (with solutions)
10 Puzzles Brief (with solutions)
 
MLB Teams Logic Puzzle Solution
MLB Teams Logic Puzzle SolutionMLB Teams Logic Puzzle Solution
MLB Teams Logic Puzzle Solution
 
Recreational mathematics for MichMATYC 10 10
Recreational mathematics for MichMATYC 10 10Recreational mathematics for MichMATYC 10 10
Recreational mathematics for MichMATYC 10 10
 
Math activities
Math activitiesMath activities
Math activities
 
Puzzles of mathematics
Puzzles of mathematicsPuzzles of mathematics
Puzzles of mathematics
 
Recreational mathematics aditya verma xc
Recreational mathematics       aditya verma   xcRecreational mathematics       aditya verma   xc
Recreational mathematics aditya verma xc
 
Puzzles
PuzzlesPuzzles
Puzzles
 
Math is Fun!
Math is Fun!Math is Fun!
Math is Fun!
 
Launch task ppt
Launch task pptLaunch task ppt
Launch task ppt
 
Easy maths riddles with answers
Easy maths riddles with answersEasy maths riddles with answers
Easy maths riddles with answers
 
Math activities
Math activitiesMath activities
Math activities
 

Similar to Functional sudoku

Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
Scala collection
Scala collectionScala collection
Scala collection
Knoldus Inc.
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
ssuser92d367
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
Philip Schwarz
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
Angelo Leto
 
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
ERIKAMARIAGUDIOSANTA
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
UadAccount
 
Oct27
Oct27Oct27
Oct27
Tak Lee
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
Proyecto parcial 2
Proyecto parcial 2Proyecto parcial 2
Proyecto parcial 2
KevinGuerra26
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
•sreejith •sree
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
Mandeep Singh
 
Object Oriented Design and Programming Unit-05
Object Oriented Design and Programming Unit-05Object Oriented Design and Programming Unit-05
Object Oriented Design and Programming Unit-05
sivakumarmcs
 

Similar to Functional sudoku (20)

Scala Collections
Scala CollectionsScala Collections
Scala Collections
 
Scala collections
Scala collectionsScala collections
Scala collections
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala collection
Scala collectionScala collection
Scala collection
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
cluod.pdf
cluod.pdfcluod.pdf
cluod.pdf
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Sequence and Traverse - Part 2
Sequence and Traverse - Part 2Sequence and Traverse - Part 2
Sequence and Traverse - Part 2
 
Introduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with sparkIntroduction to parallel and distributed computation with spark
Introduction to parallel and distributed computation with spark
 
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
Aplicaciones de espacios y subespacios vectoriales en la carrera de tecnologi...
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
Oct27
Oct27Oct27
Oct27
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Proyecto parcial 2
Proyecto parcial 2Proyecto parcial 2
Proyecto parcial 2
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Object Oriented Design and Programming Unit-05
Object Oriented Design and Programming Unit-05Object Oriented Design and Programming Unit-05
Object Oriented Design and Programming Unit-05
 

Recently uploaded

Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 

Recently uploaded (20)

Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 

Functional sudoku

  • 1. Functional Sudoku HOW TO SOLVE SUDOKU GRIDS IN SCALA 1
  • 3. Table of content 1. Introduction 2. What is a Sudoku? 3. Brief introduction to Scala features 4. Let’s Get coding! 3
  • 4. 1-Introduction – Who am I?  I’m Cesar Tron-Lozai  I work for a Startup in London  I love Java, Scala and Functional Programming 4
  • 5. 1-Introduction – What will talk about?  How to solve Sudoku grids using Functional Idioms in Scala  Have fun and hopefully learn something  Disclaimers:  I’m no Scala experts => please be tolerant if the Scala code smells  Original idea from Anton Loss (@avloss) developed during a London Scala Users Group in London  It is not meant to be the fastest solution to solve a grid  It does not solve hard grids (where backtracking is required) 5
  • 6. 2 – What’s Sudoku 6
  • 7. 2 – What’s Sudoku? - The rules  9 x 9 grids  Goal is to fill the whole grid  All rows must have 1-9 once  All columns must have 1-9 once  All squares must have 1-9 once Image credit: Wikipedia 7
  • 8. 3 – Brief introduction to Scala features 8
  • 9. 3 – Scala – Case Classes  Case classes  “regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching”  Immutable  Automatic constructors and getters sealed trait Shape case class Circle(d: Double) extends Shape case class Rectangle(w: Double, h: Double) extends Shape val circle = Circle(22) val rectangle = Rectangle(10, 20) def shapePrint(shape: Shape) : String = shape match{ case Circle(d) => s"Circle [d=$d]" case Rectangle(w, h) => s"Rectangle [w= $w, h=$h]" } 9
  • 10. 3 – Scala – Filter operator def filter[A](as: Vector[A])(f: A => Boolean) : Vector[A] val l1 = Vector(1, 2, 3) l1.filter(x => x % 2 == 0) //= Vector(2) 10
  • 11. 3 – Scala – Map operator def map[A, B](as: Vector[A])(f: A=>B) : Vector[B] val l1 = Vector(1, 2, 3) l1.map(x => 2 * x) //= Vector(2, 4, 6) 11
  • 12. 3 – Scala – Flat Map operator def flatMap[A, B](as: Vector[A])(f: A => Vector[B]) : Vector[B] val l1 = Vector(1, 2, 3) val l2 = l1.flatMap(x => Vector(x, x)) //l2 = Vector(1, 1, 2, 2, 3, 3) 12
  • 13. 3 – Scala – Grouped Operator val row1 = Vector(1, 2, 3, 4): Vector[Int] val row2 = Vector(5, 6, 7, 8): Vector[Int] val row3 = Vector(9, 10, 11, 12): Vector[Int] val row4 = Vector(13, 14, 15, 16): Vector[Int] val matrix = Vector(row1, row2, row3, row4): Vector[Vector[Int]] val g = matrix.grouped(2).toList /* g = [ [[1, 2, 3, 4],[5, 6, 7, 8]], [[9, 10, 11, 12], [9, 10, 11, 12]] ] */ var rowIndex = 1 var colIndex = 0 val square = g(rowIndex) .flatMap(row => row.grouped(2).toList(colIndex)) : Vector[Int] /* square = [9, 10, 13, 14] */ 13
  • 14. 3 – Scala – Tuples val tuple = (1, 2, 3) //val tuple = Tuple3(1, 2, 3) val e1 = tuple._1 //=1 val e2 = tuple._2 //=2 val e3 = tuple._3 //=3 14
  • 15. 3 – Scala – ZipWithIndex operator val list = Vector("a", "b", "c") val zipped = list.zipWithIndex //zipped = Vector((a,0), (b,1), (c,2)) 15
  • 16. 3 – Scala – Transpose Operator  Transpose  Transform a m x n matrix into a n x m matrix val row1 = Vector (1, 2) : Vector[Int] val row2 = Vector(3, 4) : Vector[Int] val row3 = Vector(5, 6) : Vector[Int] val matrix = Vector(row1, row2, row3) : Vector[Vector[Int]] val t = matrix.transpose //t = Vector(Vector(1, 3, 5), Vector(2, 4, 6)) Example credit: Wikipedia 16
  • 17. 4 – Sudoku Solver 17
  • 18. 4 – Solver – Cell class sealed trait Cell case class Fixed(e: Int) extends Cell case class Undetermined(values: List[Int]) extends Cell A grid is modelled as: Vector[Vector[Cell]] 18
  • 19. 4 – Solver – Sudoku Class case class Sudoku(grid: Vector[Vector[Cell]]) { def isValueAllowedInRow(position: (Int, Int), value: Int): Boolean = ??? def isValueAllowedInColumn(position: (Int, Int), value: Int): Boolean = ??? def isValueAllowedInSquare(position: (Int, Int), value: Int): Boolean = ??? } 19
  • 20. 4 – Solver – Row logic /** * Returns true if the given value, at the given position, is allowed within its row. * Logically this is true if the row doesn't already contain a Fixed cell with the given value * * @param position The position of the cell being checked * @param value The value to test * @return true if the value is allowed in that cell */ def isValueAllowedInRow(position: (Int, Int), value: Int): Boolean = !grid(position._1).contains(Fixed(value)) 20
  • 21. 4 – Solver – Column logic /** * Returns true if the given value, at the given position, is allowed within its column. * Logically this is true if the column doesn't already contain a Fixed cell with the given value * * @param position The position of the cell being checked * @param value The value to test * @return true if the value is allowed in that cell */ def isValueAllowedInColumn(position: (Int, Int), value: Int): Boolean = { val t = grid.transpose !t(position._2).contains(Fixed(value)) } 21
  • 22. 4 – Solver – Square logic /** * Returns true if the given value, at the given position, is allowed within its square. * Logically this is true if the square doesn't already contain a Fixed cell with the given value * * @param position The position of the cell being checked * @param value The value to test * @return true if the value is allowed in that cell */ def isValueAllowedInSquare(position: (Int, Int), value: Int): Boolean = { val ci = position._1 / 3 val cj = position._2 / 3 val squareCells = grid.grouped(3).toList(ci).flatMap { row => row.grouped(3).toList(cj) } !squareCells.contains(Fixed(value)) } 22
  • 23. 4 – Solver – Logic wrapper /** * Returns true of the given value, at the given position is allowed. This methods combine the row, column and * square strategies * * @param position The position of the cell being checked * @param value The value to test * @return true if the value is allowed in that cell */ def isValueAllowed(position: (Int, Int), value: Int): Boolean = isValueAllowedInRow(position, value) && isValueAllowedInColumn(position, value) && isValueAllowedInSquare(position, value) 23
  • 24. 4 – Solver – And finally def filter(): Sudoku = { val filtered: Vector[Vector[Cell]] = grid .zipWithIndex .map {case (row, rowIdx) => row .zipWithIndex .map { case (Undetermined(values), colIdx) => Undetermined(values.filter(v => isValueAllowed((rowIdx, colIdx),v))) case (x, _) => x } .map { case Undetermined(values) if values.size == 1 => Fixed(values.head) case x => x } } if (filtered == grid) this else Sudoku(filtered).filter() } 24
  • 25. References  Code available on Github: https://github.com/cesartl/sudoku  It contains a bit more error handling  Tested again 100 simple Sudokus (https://qqwing.com/instructions.html)  Thank you:  Anton Loss (@avloss)  Julien Truffaut (https://github.com/julien-truffaut) 25