Lecture-1-3-Theg.scala 9.85 KB
Newer Older
Jim Newton's avatar
Jim Newton committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
// Copyright (c) 2020 EPITA Research and Development Laboratory
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package lecture

object Theg {

  def checkEdge(n:Int, src:Int,dst:Int):Unit = {
    assert(src >= 0, s"edge src=$src must be >=0")
    assert(dst >= 0, s"edge dst=$dst must be >=0")
    assert(src < n, s"edge src=$src must be < n=$n")
    assert(dst < n, s"edge dst=$dst must be < n=$n")
  }

  // we begin assuming the edges are DIRECTED. this makes the code
  //   simpler.   Later we will parameterize the function to all
  //   directed or undirected graphs.

  // tail recursive function
  //   iterates on List input
  //   produces Array output
  //   uses .isEmpty, .head, and .tail to examine List and terminate recursion
  //   uses .updated to extend Array
  //   uses + to extend Set
  def makeAdj_1(n:Int, edges:List[(Int,Int)]):Array[Set[Int]] = {
    val adj = Array.fill(n)(Set[Int]())

    @scala.annotation.tailrec
    def init(edges:List[(Int,Int)], adj:Array[Set[Int]]):Array[Set[Int]] = {
      if (edges.isEmpty)
        adj
      else {
        val (src,dst) = edges.head
        checkEdge(n,src,dst)
        init(edges.tail,
             adj.updated(src,adj(src)+dst))
      }
    }
    init(edges,adj)
  }

  // tail recursive function
  //   iterates on List input
  //   produces Array output
  //   * uses pattern matching to examine list and terminate recursion
  //   uses .updated to extend Array
  //   uses + to extend Set
  def makeAdj_2(n:Int, edges:List[(Int,Int)]):Array[Set[Int]] = {
    val adj = Array.fill(n)(Set[Int]())

    @scala.annotation.tailrec
    def init(edges:List[(Int,Int)], adj:Array[Set[Int]]):Array[Set[Int]] = {
      edges match {
        case (src,dst)::tail =>
          checkEdge(n,src,dst)
          init(tail,
               adj.updated(src,adj(src)+dst))
        case List() =>
          adj
      }
    }
    init(edges,adj)
  }

  // tail recursive function
  //   * iterates on Array input
  //   produces Array output
  //   * uses .size and Array access by index to examine input Array
  //   uses .updated to extend Array
  //   uses + to extend Set
  def makeAdj_3(n:Int, edges:Array[(Int,Int)]):Array[Set[Int]] = {
    val adj = Array.fill(n)(Set[Int]())

    @scala.annotation.tailrec
    def init(i:Int, adj:Array[Set[Int]]):Array[Set[Int]] = {
      if (i == edges.size)
        adj
      else {
        val (src,dst) = edges(i)
        checkEdge(n,src,dst)
        init(i+1,
             adj.updated(src,adj(src)+dst))
      }
    }
    init(0,adj)
  }

  // tail recursive function
  //   * iterates on List input
  //   * produces Map output
  //   * uses pattern matching on List
  //   * uses + to extend Map
  //   uses + to extend Set
  def makeAdj_4(n:Int, edges:List[(Int,Int)]):Map[Int,Set[Int]] = {
    val adj= (0 to n-1).map{ i => i -> Set[Int]()}.toMap

    @scala.annotation.tailrec
    def loop(adj:Map[Int,Set[Int]],edges:List[(Int,Int)]):Map[Int,Set[Int]] = {
      edges match {
        case (src,dst)::es =>
          loop(adj + (src -> (adj(src)+dst)),es)
        case _ => adj
      }
    }
    loop(adj,edges)
  }

  // * uses tabulate to iterate
  //   * iterates on Array input
  //   * produces Array output
  //   * computes Array once, not iteratively, not recursively
  //   * uses .filter .toSet to compute set of destination vertices
  def makeAdj_5(n:Int, edges:Array[(Int,Int)]):Array[Set[Int]] = {
    def connectionsTo(i:Int):Set[Int] = {
      (0 until n).filter {
        j => edges.exists { case (src, dst) => src == i && dst == j }
      }.toSet
    }
    Array.tabulate(n)(connectionsTo)
  }

  // uses tabulate to iterate
  //   iterates on Array input
  //   produces Array output
  //   computes Array once, not iteratively, not recursively
  //   uses .filter .toSet to compute set of destination vertices
  //   * uses capital letters in pattern matching
  def makeAdj_6(n:Int, edges:Array[(Int,Int)]):Array[Set[Int]] = {
    def connectionsTo(S:Int):Set[Int] = {
      (0 until n).filter {
        D => edges.exists {
          case (S, D) => true
          case _ => false
        }
      }.toSet
    }
    Array.tabulate(n)(connectionsTo)
  }

  // tail recursive function
  //   iterates on List input
  //   produces Map output
  //   uses pattern matching on List
  //   uses + to extend Map
  //   uses + to extend Set
  //   * omits initialization of Map, just uses Map() and .getOrElse
  def makeAdj_7(edges:List[(Int,Int)]):Map[Int,Set[Int]] = {

    @scala.annotation.tailrec
    def loop(adj:Map[Int,Set[Int]],edges:List[(Int,Int)]):Map[Int,Set[Int]] = {
      edges match {
        case (src,dst)::es =>
          loop(adj + (src -> (adj.getOrElse(src,Set())+dst)),es)
        case _ => adj
      }
    }
    loop(Map(),edges)
  }

  // * uses .foldLeft
  //   iterates on List input
  //   produces Map output
  //   uses + to extend Map
  //   uses + to extend Set
  //   omits initialization of Map, just uses Map() and .getOrElse
  def makeAdj_8(edges:List[(Int,Int)]):Map[Int,Set[Int]] = {
    edges.foldLeft(Map[Int,Set[Int]]()){
      case (adj,(src,dst)) =>
        adj + (src -> (adj.getOrElse(src,Set())+dst))
    }
  }

  // uses .foldLeft
  //   * iterates on Array input
  //   * code copied exactly from makeAdj_7
  //   produces Map output
  //   uses + to extend Map
  //   uses + to extend Set
  //   omits initialization of Map, just uses Map() and .getOrElse
  def makeAdj_9(edges:Array[(Int,Int)]):Map[Int,Set[Int]] = {
    edges.foldLeft(Map[Int,Set[Int]]()){
      case (adj,(src,dst)) =>
        adj + (src -> (adj.getOrElse(src,Set())+dst))
    }
  }

  // uses .foldLeft
  //   * iterates on Seq input or List input
  //   * code copied exactly from makeAdj_7/makeAdj_8
  //   produces Map output
  //   uses + to extend Map
  //   uses + to extend Set
  //   omits initialization of Map, just uses Map() and .getOrElse
  def makeAdj_10(edges:Seq[(Int,Int)]):Map[Int,Set[Int]] = {
    edges.foldLeft(Map[Int,Set[Int]]()){
      case (adj,(src,dst)) =>
        adj + (src -> (adj.getOrElse(src,Set())+dst))
    }
  }

  // uses .foldLeft
  //   * parameterizes the vertex type, no longer Int, now is V
  //   * iterates on Seq[A] input or List[A] input
  //   produces Map output
  //   uses + to extend Map
  //   uses + to extend Set
  //   omits initialization of Map, just uses Map() and .getOrElse
  def makeAdj_11[V](edges:Seq[(V,V)]):Map[V,Set[V]] = {
    edges.foldLeft(Map[V,Set[V]]()){
      case (adj,(src,dst)) =>
        adj + (src -> (adj.getOrElse(src,Set[V]())+dst))
    }
  }

  // same as makeAdj_11, but assumes UNDIRECTED edges
  def makeAdj_12[V](edges:Seq[(V,V)]):Map[V,Set[V]] = {
    edges.foldLeft(Map[V,Set[V]]()){
      case (adj,(src,dst)) =>
        adj +
          (src -> (adj.getOrElse(src,Set[V]())+dst)) +
          (dst -> (adj.getOrElse(dst,Set[V]())+src))
    }
  }

  // combine makeAdj_11 and makeAdj_12 with a Boolean indicating
  // whether edges are interpreted as DIRECTED or UNDIRECTED
  def makeAdj_13[V](edges:Seq[(V,V)], directed:Boolean):Map[V,Set[V]] = {
    edges.foldLeft(Map[V,Set[V]]()){
      case (adj,(src,dst)) =>
        val m1 = adj + (src -> (adj.getOrElse(src,Set[V]())+dst))
        if (directed)
          m1
        else
          m1 + (dst -> (adj.getOrElse(dst,Set[V]())+src))
    }
  }

  // we will cover this solution in a later lecture
  def makeAdj_14[V](edges:Seq[(V,V)], directed:Boolean):Map[V,Set[V]] = {
    val edges2 = if ( directed )
      edges
    else
      edges ++ edges.map{case (src,dst) => (dst,src)}
    edges2.groupBy{e => e._1}.map{
      case (src,edges) => src -> edges.map{e=>e._2}.toSet
    }
  }

  def main(args: Array[String]): Unit = {
    println("1: " + makeAdj_1(3, List((0,1), (1,2))).mkString(","))
    println("2: " + makeAdj_2(3, List((0,1), (1,2))).mkString(","))
    println("3: " + makeAdj_3(3, Array((0,1), (1,2))).mkString(","))
    println("4: " + makeAdj_4(3, List((0,1), (1,6), (0,2))))
    println("5: " + makeAdj_5(3, Array((0,1), (1,2), (0,2))).mkString(","))
    println("6: " + makeAdj_6(3, Array((0,1), (1,2), (0,2))).mkString(","))
    println("7: " + makeAdj_7(List((0,1), (1,6), (0,2))))
    println("8: " + makeAdj_8(List((0,1), (1,6), (0,2))))
    println("9: " + makeAdj_9(Array((0,1), (1,6), (0,2))))
    println("10: " + makeAdj_10(List((0,1), (1,6), (0,2))))
    println("10: " + makeAdj_10(Array((0,1), (1,6), (0,2))))
    println("11: " + makeAdj_11(Array((0,1), (1,6), (0,2))))
    println("11: " + makeAdj_11(Array(("fred","jane"), ("sally","rita"), ("rita","fred"))))
    println("11: " + makeAdj_11(List(("fred","jane"), ("sally","rita"), ("rita","fred"))))
    println("12: " + makeAdj_12(List(("fred","jane"), ("sally","rita"), ("rita","fred"))))
    println("13a: " + makeAdj_13(List(("fred","jane"), ("sally","rita"), ("rita","fred")), true))
    println("13b: " + makeAdj_13(List(("fred","jane"), ("sally","rita"), ("rita","fred")), false))
    println("14: " + makeAdj_14(List(("fred","jane"), ("sally","rita"), ("rita","fred")), false))
  }
}