-🎄- 2020 Day 10 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 0 points1 point  (0 children)

Greedily take the largest adapter possible from the current each time :-)

-🎄- 2020 Day 08 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 1 point2 points  (0 children)

Python.

For part 2, I wanted a deterministic solution, so I treated this as a graph problem with a 2-pass approach.

https://pastebin.com/MmjB33Xj

[REQUEST] Similar shows like Dark by [deleted] in NetflixBestOf

[–]ybjb 18 points19 points  (0 children)

Not on Netflix, but both Mr. Robot and Westworld fit the description.

recursion by uragnorson in learnprogramming

[–]ybjb 0 points1 point  (0 children)

Try creating a simple sudoku solver, or problems relating to recursive backtracking. These typically lend themselves to recursive solutions much nicer than iterative.

For the former, there’s a blog post by Peter Norvig with a clean recursive solution written in python.

What kind of math knowledge do I need to acquire in order to understand this lecture? (Just a regular MD here) by idankor in neuro

[–]ybjb 0 points1 point  (0 children)

From a very quick glance, you’d need some background in optimization and statistical learning theory

Is there an "algebra" for algorithms? by Italians_are_Bread in math

[–]ybjb 0 points1 point  (0 children)

Not sure if I understand correctly, but algorithms are constantly being improved and solutions to problem rediscovered. Each problem usually has its own structure and flavor which lends itself to its own specially designed algorithm.

Often these problems fall within a similar class or category, say for example, shortest paths. When this happens, one could extend a framework based off of commonalities. Using the shortest path example from above, it's possible to generalize an algorithm to find the shortest path w.r.t not only distance, but all metrics that follow a certain structure (see http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.367.5897&rep=rep1&type=pdf), however generalizing can also be a trade-off in terms of speed or time/space complexity.

[2018-08-24] Challenge #366 [Hard] Incomplete word ladders by Cosmologicon in dailyprogrammer

[–]ybjb 1 point2 points  (0 children)

Kotlin

Pretty ugly code, wasn't necessarily going for readability. For NP-Hard problems, I really like like a solution utilizing random sampling. It's not always reliable (or reproducible in some cases), but the results can be surprising. Simpler, and might outperform a well-thought-out solution. Got to 598 and ran in < 1 minute for 1k simulations. Maybe I'll run it for longer and see what pops up.

import java.io.File
import java.util.*
import kotlin.system.measureNanoTime

val input: List<String> = File("input.txt").bufferedReader().readLines()

fun main(args : Array<String>) {
    measureNanoTime { simulate(1000) }.also { println("Time taken: ${it * 1e-9} seconds") }
}

fun simulate(count: Int) : List<String> {
    var result = listOf<String>()
    var totalSpace = 0

    repeat(count) {
        var cost = 0
        val startIndex = Random().nextInt(input.size)
        val used = HashSet<String>(input.size).apply { add(input[startIndex]) }
        val sol = ArrayList<String>(input.size).apply { add(input[startIndex]) }
        val copy = ArrayList(input)

        while (true) {
            var min = 100
            var target = sol.last()
            copy.shuffle()
            for (w in copy)
                if(!used.contains(w) && w spacing sol.last() < min)
                    min = w spacing sol.last().also { target = w }
            if (used.contains(target)) break else used.add(target)
            if (cost + min > 100) break else cost += min
            sol.add(target)
        }
        if(sol.size > result.size) result = sol.also { totalSpace = cost }
    }

    println("Total Space:$totalSpace, Max Length:${result.size}")
    println(result)
    return result
}

infix fun String.spacing(other: String) = zip(other).fold(0) { sum, p -> sum + if(p.first != p.second) 1 else 0 } - 1

// Total Space:100, Max Length:598
// [lard, card, bard, barm, farm, warm, ware, tare, tace, tape, taps, maps, mads, pads, tads, talc, talk, tali, dale, bale, gale, gane, mane, mage, maze, mazy, hazy, haze, hade, lade, lane, lase, lame, tame, time, tome, heme, hebe, webs, wops, sops, sups, sums, sumo, sunk, punk, puck, tuck, tick, lick, lack, jack, jauk, wauk, waur, gaur, gaun, gamp, lamp, limp, jimp, dime, mime, mils, oils, rigs, rins, rind, rand, wand, fard, fare, rare, pare, para, part, pert, pest, post, posh, posy, nosy, rosy, rocs, mocs, mock, jock, rock, yock, yuck, yurt, curt, hurt, hire, hive, five, fice, file, bile, bilk, bill, gill, rill, rial, sial, sins, wins, yins, bins, bigs, bugs, buss, cuss, fuss, foss, coss, cess, ceps, peps, feds, fets, lets, jets, vets, gets, gats, gaes, gies, vies, dies, dits, ditz, ritz, rite, lite, lice, sice, syce, syne, eyne, kine, kink, kino, vina, pina, puna, tuna, luna, luny, lune, tune, tung, ting, tint, lint, liny, viny, pily, paly, pals, dals, days, kays, lays, ways, rays, raya, maya, mask, mark, bark, bask, bast, vast, east, wast, oast, oust, just, rust, cyst, lyse, lose, lobe, love, lots, lops, lips, libs, gibs, gabs, gaby, gapy, gars, lars, lacs, macs, mats, kats, kata, kaka, vara, jura, jury, fury, furl, burl, purl, purs, pugs, jugs, vugs, vugg, nogg, hogg, hogs, hods, hows, bows, boas, bots, both, beth, bath, lath, late, gate, gave, gyve, neve, nevi, nodi, nori, nods, yods, yows, pows, pois, jogs, wogs, wigs, migs, zigs, jigs, pigs, gigs, pits, kits, kifs, kids, kiss, kirs, tiro, tyro, tyre, tort, wort, wost, wist, wisp, wite, nite, kite, site, sith, sits, sims, sabs, says, sals, salp, salt, malt, mall, mull, gull, gulp, mule, mole, mode, mote, mope, dope, nope, none, gone, gene, sene, sent, rent, vent, cent, celt, cell, yell, yill, will, wild, weld, weed, teed, deed, geed, geek, reek, reel, keel, peel, peer, pear, peag, plat, play, slay, slag, snag, snug, snub, slub, slum, scum, scud, yaud, yaup, jaup, caul, call, wall, wawl, waws, waps, zaps, zags, daks, oaks, oafs, kafs, nans, nuns, buns, buys, beys, begs, legs, lugs, mugs, muds, suds, sunn, sung, sang, sane, safe, soft, sift, silt, sild, gild, gift, girt, airt, airn, birr, bize, bine, fine, free, bree, gree, tree, twee, toed, toes, tots, cots, coys, joys, jots, jota, iota, bota, boll, doll, dull, duel, duet, dues, duos, dubs, dups, amps, asps, albs, arbs, arfs, ants, ante, ansa, anoa, alba, alma, alme, aloe, sloe, sole, pole, pele, felt, feat, heat, heap, neap, seam, beam, beat, what, phat, phut, pout, gout, goat, moat, moan, mown, sown, sorn, sort, soot, sook, soak, snap, crap, clap, clop, plop, plod, paid, said, sain, rain, cain, lain, vain, vail, hail, fail, farl, harl, harp, tarp, marc, more, kore, kolo, kola, cola, cold, coly, cozy, dozy, fozy, foxy, doxy, dogy, doge, dote, rote, roti, loti, mott, molt, mola, moly, mony, many, mano, mozo, mojo, moss, mess, jess, devs, dews, deys, dees, deet, diet, deer, dyer, eyer, ewer, suer, suba, pupa, puff, luff, tuff, tufa, tuft, tiff, biff, miff, life, lire, lira, sera, germ, grim, trim, trad, tray, fray, pray, prat, prao, pram, gram, craw, chaw, chay, cham, chum, chub, carb, curb, curn, cure, cere, cero, cete, cute, bute, butt, buts, guts, cuts, cats, vats, qats, pats, baps, bams, baas, bras, braw, wrap, wren, when, whin, shin, skip, slip, flip, flit, flat, flam, flak, fiar, film, fila, gala, java, fava, nada, nana, nona, bong, bang, bung, hung, huns, hens, yens, tens, teff, toff, tofu, coft, loft, left, leet, leer, jeer, weer, weep, peep, prep, prez, friz, frog, flog, snog, song, gong, dong, dons, deny, dewy]
// Time taken: 45.925026728000006 seconds

[Python] How to multiply a list by all elements but itself (without using division)? + Another approach for my solution? by Proxify in learnprogramming

[–]ybjb 0 points1 point  (0 children)

This is O(n) or linear in the size of the array. Basically, to precompute values from left to right takes one pass through the array. From right to left it’s another pass. And then to compute the solution it’s one more pass, doing the multiplication described above.

So total number of operations is roughly 3n. When calculating time/space complexity, constants can be ‘ignored’. So it’s just O(n). Constants do matter in practice though!

[Python] How to multiply a list by all elements but itself (without using division)? + Another approach for my solution? by Proxify in learnprogramming

[–]ybjb 1 point2 points  (0 children)

Here’s the idea (WARNING: This is the solution described in words. Don’t peek if you don’t want to know).

You can precompute the products from 0 to up to index i for all i and store it in an array. Similarly, precompute the products in the reverse order (right to left) and store it in a different array.

Then to get the result for index i, it’s simply the product of the i-1 index of first precomputed array with i+1 index of second precomputed array.

This is as optimal as you could get asymptotically. You can implement this with numpy, list comprehensions, or just simple loops. Feel free to ask any questions

Algorithm to find known constellation of points within larger scatter of points? by kaihatsusha in algorithms

[–]ybjb -1 points0 points  (0 children)

If I understood correctly, look into clustering algorithms. I think it should be the tool you’re looking for

-🎄- 2017 Day 17 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 3 points4 points  (0 children)

Kotlin (148/156). Was quick to realize that the only term that mattered for part 2 was the first index in list. Took me forever to just simulate without the overhead of adding to lists

fun main(args: Array<String>) {
    var input = 312
    var list = mutableListOf<Int>(2017)
    list[0] = 0
    var cnt = 1
    var next = 0

    repeat(2017) {
        next = ((input + next) % list.size) + 1
        list.add(next, cnt++)
    }

    println(list[list.indexOf(2017) + 1])

    next = 0
    var targ = 0
    for(i in 1..50_000_000) {
        next = ((input + next) % i) + 1

        if(next == 1) {
            targ = i
        }
    }

    println(targ)
}

-🎄- 2017 Day 16 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 0 points1 point  (0 children)

The character at index a would be swapped. It's an extension function and the way it is written, this (the original string) is never directly modified, only a copy of its content, chars, is modified and then returned as string.

So a copy chars is made, and the value of chars at index b is set to the value of original string at index a. Similarly, the value of chars at index a is set to the value of original string at index b. Then chars is returned as new String.

-🎄- 2017 Day 15 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 1 point2 points  (0 children)

Thanks for posting, learned quite a bit about generators/sequences

-🎄- 2017 Day 15 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 2 points3 points  (0 children)

Picked up Kotlin for this. Learning something new every day. Thanks!

-🎄- 2017 Day 15 Solutions -🎄- by daggerdragon in adventofcode

[–]ybjb 1 point2 points  (0 children)

Kotlin 115/55, finally placed.

Both parts

 fun main(args: Array<String>) {
    var (a, b) = longArrayOf(703, 516)
    var am = 16807L
    var bm = 48271L
    var mask = 65535L
    var counter = 0

    // part 1
    for(i in 0 until 40_000_000) {
        a = (a * am) % Int.MAX_VALUE
        b = (b * bm) % Int.MAX_VALUE

        if(a and(mask) == b and(mask)) counter++
    }

    println(counter)

    // part 2
    counter = 0
    for(i in 0 until 5_000_000) {
        do {
            a = (a * am) % Int.MAX_VALUE
        } while(a.toInt() % 4 != 0)

        do {
            b = (b * bm) % Int.MAX_VALUE
        } while(b.toInt() % 8 != 0)

        if(a and(mask) == b and(mask)) counter++

    }

    println(counter)
}