SVGコードゴルフ

圧縮アルゴリズムの気持ちになるですよ

推測するな計測せよに基づき最適化プログラムをでっちあげる。

import java.io.{BufferedReader, ByteArrayInputStream, ByteArrayOutputStream, InputStreamReader}
import java.nio.charset.Charset
import java.util.zip._

object GZ {
  def compress(in: String, charset: String) = {
    val buf = new ByteArrayOutputStream()
	val out = new GZIPOutputStream(buf)
    val bytes = in.getBytes(charset)
	out.write(bytes, 0, bytes.length)
	out.close
    buf.toByteArray
  }
}

object Svg {
  def toString(data: List[(String, List[String])]) = {
    var s = """<svg xmlns="http://www.w3.org/2000/svg" width="600" height="250" stroke-width="16" fill="none" stroke="#4a87ee">"""
    for ((tag, elms) <- data) {
      s += "<" + tag
      for (e <- elms)
        s += " " + e
      s += "/>"
    }
    s += """</svg>"""
    s
  }

  var min = Int.MaxValue
  var minSvg: String = null

  def optOne(data: List[(String, List[String])], svg: List[(String, List[String])]): Unit = {
    data match {
      case e :: es =>
        val (tag, attrs) = e
        for (as <- attrs.permutations) {
          optOne(es, (tag, as) :: svg)
        }
      case Nil =>
        val s = toString(svg)
        val size = GZ.compress(s, "UTF-8").length
        if (size < min) {
          min = size
          minSvg = s
          println(minSvg + " --> " + min)
        }
    }
  }

  def opt(data: List[(String, List[String])]) = {
    for (per <- data.permutations) {
      optOne(per, Nil)
    }
  }

  def main(args: Array[String]): Unit = {
    val data = List(("path", List("""d="m173 102a51 51 0 1 1-13-30m20 37h-53"""")),
      ("circle", List("""cy="128"""", """r="32"""", """cx="227"""", """stroke="#d83038"""")),
      ("circle", List("""cy="128"""", """r="32"""", """cx="313"""", """stroke="#f4c022"""")),
      ("path", List("""d="m401 160a31 31 0 1 1 0-61m-4 0a24 29 0 1 1 0 61m26-67v79m-1-12a20 20 0 1 1-52 17"""")),
      ("path", List("""d="m449 51v115"""", """stroke="#4ab95a"""")),
      ("path", List("""d="m529 118a30 30 0 1 0-2 24m5-32-62 28"""", """stroke="#d83038"""")))
    val s = toString(data)
    println(s + " --> " + GZ.compress(s, "UTF-8").length)
    opt(data)
    println(minSvg + " --> " + min)
    // for (c <- GZ.compress(s, "UTF-8"))
    //   println(c)
    println(toString(data))
  }
}
<svg xmlns="http://www.w3.org/2000/svg" width="600" height="250" stroke-width="16" fill="none" stroke="#4a87ee">
<circle cx="313" r="32" stroke="#f4c022" cy="128"/>
<circle cx="227" r="32" stroke="#d83038" cy="128"/>
<path d="m449 51v115" stroke="#4ab95a"/>
<path d="m173 102a51 51 0 1 1-13-30m20 37h-53"/>
<path d="m529 118a30 30 0 1 0-2 24m5-32-62 28" stroke="#d83038"/>
<path d="m401 160a31 31 0 1 1 0-61m-4 0a24 29 0 1 1 0 61m26-67v79m-1-12a20 20 0 1 1-52 17"/>
</svg>

これによってgzip後のサイズを269バイトにまで削減できる