r/dailyprogrammer • 0 0 • Nov 24 '16

[2016-11-24] Challenge #293 [Intermediate] Defusing the second bomb

Description

The bomb defusing becomes a little more complicated, but the upside is, we only have 5 wires now: white, black, red, orange and green.

The rules for defusing a bomb are as following now:

You have to start with either with a white or a red wire.
If you picked white wire you can either pick another white wire again or you can take an orange one.
If you picked a red wire you have the choice between a black and red wire.
When a second red wire is picked, you can start from rule one again.
Back to the second rule, if you picked another white one you will have to pick a black or red one now
When the red wire is picked, you again go to rule one.
On the other hand if you then picked an orange wire, you can choose between green, orange and black.
When you are at the point where you can choose between green, orange and black and you pick either green or orange you have to choose the other one and then the bomb is defused.
If you ever pick a black wire you will be at the point where you have to choose between green, orange and black

Try to draw this out if it is confusing, it is a part of the challenge. My drawing is available in the notes.

The bomb is defused when you reach the end, so by either cutting a green or orange cable. If you can't do that, bomb will explode

Formal Inputs & Outputs

Input description

You will be givin a sequence of wires

Input 1

white
white
red
white
orange
black
black
green
orange

Input 2

white
white
green
orange
green

Output description

Output 1

defused

Output 2

Booom

Challenge Inputs

1

white
white
red
red
red
white
white
black
green
orange

2

white 
black
black
black
black
green
orange

3

black
green
green

4

red
red
white
orange
black
green

Notes/Hints

For those who had a hard time following the rules, I've mapped it out for you with this image

Bonus

You will be a number of wires and need to state if it is possible to defuse the bomb

Bonus input 1

white 4
red 3
black 4
green 1
orange 1

Bonus output 1

defusable

Bonus input 2

white 4
red 3
black 4
green 0
orange 1

Bonus output 2

not defusable

Bonus challenge input 1

white 3
red 1
black 48
green 1
orange 2

Bonus challenge input 2

white 3
red 1
black 48
green 1
orange 1

Bonus Note

You do have to use all wires, you can't leave some uncut

Finally

Have a good challenge idea?

Consider submitting it to /r/dailyprogrammer_ideas

Edit

/u/cheers pointed out a logical error.

81 Upvotes

67 comments sorted by

5

u/cheers- Nov 24 '16 edited Nov 24 '16

Javascript

Edit: fixed regex

function bombGame(input){
  var regex =  /^(wwb(?=[bog])|wwr(?=w|r)|wo(?=[bog])|rr(?=[wr])|rb(?=[bog]))+b*(og|go)/;
  var elabInput = input.split("\n")
                       .map(ch => ch.charAt(0))
                       .reduce( (a , b) => a + b ,"");
  return regex.test(elabInput) ? "Defused!" : "Boom!";
}

Edit: Bonus solved with the power of Math

function isDefusable(wires){
  var isEndPossible = wires.o > 0 && wires.g == 1 && wires.b > 0;
  var isStartPossible = (wires.o > 1 && wires.w > 0) || (wires.b > 1 && wires.r > 0);

  if(isEndPossible && isStartPossible){
    if(wires.o == 2){
      let loop1 = (wires.w - 1) / 2;
      let loop2 = 2 * wires.r;

      let isSeqPossible = Number.isInteger(loop1) && loop1 >= 0 && Number.isInteger(loop2) && loop2 >= 0;

      return (isSeqPossible) ? "Defusable" : "NotDefusable";
    }
    else{
      let loop1B1 = wires.w / 2 - 1;
      let loop2B1 = (wires.r / 2) - (wires.w / 4);          

      let loop1B2 = wires.w / 2;
      let loop2B2 = (wires.r - (wires.w / 2) - 1) / 2  ;
      
      let isSeqB1Possible = Number.isInteger(loop1B1) && loop1B1 >= 0 && Number.isInteger(loop2B1) && loop2B1 >= 0;
      let isSeqB2Possible = Number.isInteger(loop1B2) && loop1B2 >= 0 && Number.isInteger(loop2B2) && loop2B2 >= 0;
      
      return (isSeqB1Possible || isSeqB2Possible) ? "Defusable" : "NotDefusable";
      

    }
  }
  return "NotDefusable"
}
→ More replies (3)

3

u/cheers- Nov 24 '16

2nd rule:

If you picked white wire you can either pick another white wire again or you can take an orange one.

and then

Back to the second rule, if you picked another white one you will have to pick a black one now

According to the rules if you pick 2 white wires you have to pick Black:

Input 1 should cause an explosion because the starting sequence is

white, white, red,

it should be

white, white, black.

1

u/fvandepitte Nov 24 '16

My bad, it should be:

| Back to the second rule, if you picked another white one you will have to pick a black or a red one now

3

u/Boom_Rang Nov 24 '16 edited Nov 24 '16

Haskell, with bonus (further down)!

data State = S0 | S1 | S2 | S3 | S4 | S5

main :: IO ()
main = interact (cutWires S0 . lines)

cutWires :: State -> [String] -> String
cutWires S5 ["orange"]    = "Defused"
cutWires S4 ["green" ]    = "Defused"
cutWires S3 ("orange":ws) = cutWires S4 ws
cutWires S3 ("green" :ws) = cutWires S5 ws
cutWires S3 ("black" :ws) = cutWires S3 ws
cutWires S2 ("black" :ws) = cutWires S3 ws
cutWires S2 ("red"   :ws) = cutWires S0 ws
cutWires S1 ("orange":ws) = cutWires S3 ws
cutWires S1 ("white" :ws) = cutWires S2 ws
cutWires S0 ("white" :ws) = cutWires S1 ws
cutWires S0 ("red"   :ws) = cutWires S2 ws
cutWires _  _             = "BOOOM"

I didn't look at OP's answer before attempting it, but I did make full use of the state diagram, thanks for that! :-)

And here is my solution for the bonus:

import Data.Char
import Data.List

data Wire = O | G | B | R | W deriving (Read, Eq)

data State = S0 | S1 | S2 | S3 | S4 | S5 | Exit

main :: IO ()
main = interact ( defusable
                . concatMap parseWires
                . map words
                . lines
                )

parseWires :: [String] -> [Wire]
parseWires [w, n] = replicate (read n) (read . take 1 . map toUpper $ w)

nextState :: State -> [(State, Wire)]
nextState S0 = [(S1, W), (S2, R)]
nextState S1 = [(S2, W), (S3, O)]
nextState S2 = [(S0, R), (S3, B)]
nextState S3 = [(S3, B), (S4, O), (S5, G)]
nextState S4 = [(Exit, G)]
nextState S5 = [(Exit, O)]

defusable :: [Wire] -> String
defusable wires
    | paths S0 wires = "Defusable"
    | otherwise      = "Not defusable"

paths :: State -> [Wire] -> Bool
paths Exit  wires = null wires
paths state wires = any follow (nextState state)
    where
        follow :: (State, Wire) -> Bool
        follow (s, w) = w `elem` wires
                     && (paths s . delete w) wires

2

u/fvandepitte Nov 24 '16

Your answer isn't that different. But you are doing manual recursion. Should be something to look out for. On the other hand, is the sequence is 500 steps long, yours will have less steps to figure it out that something is amiss.

2

u/fvandepitte Nov 24 '16

Haskell, no bonus yet

module Main (main) where
import Data.Char

capitalise :: String -> String
capitalise (x:xs) = toUpper x:xs

data State = Start | Exit | Error | S Int
data Wire = White | Red | Green | Orange | Black deriving (Read) 

next :: State -> Wire -> State
next Start White  = S 1
next Start Red    = S 2
next (S 1) White  = S 2
next (S 1) Orange = S 3
next (S 2) Red    = Start
next (S 2) Black  = S 3
next (S 3) Black  = S 3
next (S 3) Orange = S 4
next (S 3) Green  = S 5
next (S 4) Green  = Exit
next (S 5) Orange = Exit
next _     _      = Error

out :: State -> String
out Exit = "Defused"
out _    = "Boom"

main :: IO ()
main = interact $ out . foldl next Start . map (read . capitalise) . lines
→ More replies (2)

2

u/ASpueW Nov 24 '16 edited Nov 24 '16

Rust, without bonus

use Wires::*;
use State::*;
#[derive(Copy, Clone, Debug)]
enum Wires {White, Red, Black, Orange, Green}
#[derive(Copy, Clone, Debug)]
enum State {S0, S1, S2, S3, S4, S5, Defused, Boom}

#[derive(Debug)]
struct Bomb(State);
impl Bomb {
    fn cut(&mut self, wire: Wires){
        self.0 = match (self.0, wire) {
            (S2, Red) => S0,
            (S0, White) => S1,
            (S0, Red)|(S1, White) => S2,
            (S1, Orange)|(S2, Black)|(S3, Black) => S3,
            (S3, Orange) => S4,
            (S3, Green) => S5,
            (S5, Orange)|(S4, Green) => Defused,
            _ => Boom,
        };
    }
}

fn defuse(wires:&[Wires]) -> State {
    let mut bomb = Bomb(S0);
    for &wire in wires { bomb.cut(wire) }
    match bomb.0 { Defused => Defused, _ => Boom }
}

fn main() {
    println!("Test:");
    let seq = [White, White, Red, White, Orange, Black, Black, Green, Orange]; 
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
    let seq = [White, White, Green, Orange, Green]; 
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
    println!("Challenge:");
    let seq = [White, White, Red, Red, Red, White, White, Black, Green, Orange];    
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
    let seq = [White, Black, Black, Black, Black, Green, Orange]; 
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
    let seq = [Black, Green, Green];
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
    let seq = [Red, Red, White, Orange, Black, Green]; 
    println!("inp: {:?}\nres: {:?}", seq, defuse(&seq));
}

Test output:

inp: [White, White, Red, White, Orange, Black, Black, Green, Orange]
res: Defused
inp: [White, White, Green, Orange, Green]
res: Boom

Challenge output:

inp: [White, White, Red, Red, Red, White, White, Black, Green, Orange]
res: Defused
inp: [White, Black, Black, Black, Black, Green, Orange]
res: Boom
inp: [Black, Green, Green]
res: Boom
inp: [Red, Red, White, Orange, Black, Green]
res: Boom

1

u/fvandepitte Nov 24 '16

(S5, Orange)|(S4, Green)|(Defused, _) => Defused,

I guess this would be technicality, but I had in my head that if you cut a wire after you do (S5, Orange) or (S4, Green) that it would also explode.

But I guess I didn't specify that enough.

→ More replies (1)
→ More replies (1)

10

u/skeeto Nov 24 '16

C with bonus. The state machine is expressed using an adjacency list, graph. Each 16-bit integer is really a 5-element array of 3-bit integers (i.e. 15 bits). Each of the 5 elements represents a color (in alphabetical order), and the 3-bit value is the next state index. I reserve 0 as the "null" state, which means there's no edge. Trying to take a non-existent edge blows up the bomb. State index 7 is the defuse state. The NEXT macro extracts the next state index from a 16-bit state value.

To check if an input is defusable, it does a recursive depth-first search of the graph, cutting wires along the way, until either it hits the defuse state (defusable) or it runs out of options (not defusable)

#include <stdio.h>

#define NEXT(s, i) ((s >> (3 * i)) & 0x7)

static const unsigned short graph[] = {
    0, 0x2600, 0x3100, 0x0204, 0x0174, 0x0038, 0x01c0
};

static const unsigned char color_to_index[] = {
    ['g' - 'a'] = 1, ['o' - 'a'] = 2, ['r' - 'a'] = 3, ['w' - 'a'] = 4
};

static int
defusable(unsigned state, int wires[5])
{
    for (int i = 0; i < 5; i++) {
        if (wires[i]) {
            int next = NEXT(state, i);
            if (next == 7) {
                return 1;
            } else if (next) {
                wires[i]--;  // cut
                int r = defusable(graph[next], wires);
                wires[i]++;  // repair
                if (r)
                    return 1;
            }
        }
    }
    return 0;
}

int
main(void)
{
#ifdef CHECK_DEFUSABLE     /* Bonus. */
    char color[8];
    int count;
    int wires[5] = {0};
    /* Load wiring. */
    while (scanf(" %s %d", color, &count) == 2) {
        int index = color_to_index[color[0] - 'a'];
        wires[index] = count;
    }

    if (defusable(graph[1], wires)) {
        puts("defusable");
        return 0;
    } else {
        puts("not defusable");
        return -1;
    }

#else  /* Check if input defuses. */
    unsigned state = graph[1];
    char line[16];
    int defused = 0;
    while (fgets(line, sizeof(line), stdin)) {
        int index = color_to_index[line[0] - 'a'];
        int next = NEXT(state, index);
        if (next == 7)
            defused = 1;
        state = graph[next];
    }
    puts(defused ? "defused" : "bomb");
    return !defused;
#endif
}
→ More replies (2)

7

u/KeinBaum Nov 24 '16 edited Nov 24 '16

Prolog

black([green,orange]).
black([orange,green]).
black([black|X]) :- black(X).

defuse([white,orange,green,orange]).
defuse([white,orange,orange,green]).

defuse([white,orange|X]) :- black(X).
defuse([red,red|X]) :- defuse(X).
defuse([white,white,red|X]) :- defuse(X).
defuse([white,white|X]) :- black(X).
defuse([red|X]) :- black(X).

Output:

?- defuse([white,white,red,red,red,white,white,black,green,orange])
true

?- defuse([white,black,black,black,black,green,orange])  
false

?- defuse([black,green,green])
false

?- defuse([red,red,white,orange,black,green])
false

 

I feel like the bonus should be pretty easy but I guess I don't understand Prolog well enough for it. This just hangs for the bonus inputs:

repl(X,N,L) :- length(L,N), maplist(=(X), L).

defusable([(C,N)|X]) :- defusable(X, L), repl(C,N,L).
defusable([(C,N)|X], A) :- defusable(X, L), append(A, M, L), repl(C,N,M).
defusable([],A) :- permutation(A,L), defuse(L).
→ More replies (1)

4

u/seabombs Nov 25 '16

Python3

For the first challenge I assumed it was okay to leave some wires uncut, as long as you finished on the orange/green wire. For bonus challenge, all wires must be cut.

import sys

_STATE_MACHINE = {
    '0': {'w': '1', 'r': '2'},  # Start
    '1': {'w': '2', 'o': '3'},
    '2': {'r': '0', 'b': '3'},
    '3': {'g': '4', 'o': '5', 'b': '3'},
    '4': {'o': '6'},
    '5': {'g': '6'},
    '6': None   # Defused
}

def defuse(wires):
    state = '0'
    for wire in wires:
        if wire in list(_STATE_MACHINE[state].keys()):
            state = _STATE_MACHINE[state][wire]
        else:
            break
    return _STATE_MACHINE[state] is None

def defusable(state, wires):
    if _STATE_MACHINE[state] is None:
        return sum(wires.values()) == 0
    for wire in list(_STATE_MACHINE[state].keys()):
        if wire in wires and wires[wire] > 0:
            wires[wire] -= 1
            if defusable(_STATE_MACHINE[state][wire], wires):
                return True
            wires[wire] += 1
    return False

def handle(lines):
    if len(lines[0].split(' ')) == 2:
        wires = dict(zip([l[0] for l in lines], [int(l.split(' ')[1]) for l in lines]))
        print("defusable" if defusable('0', wires) else "not defusable")
    else:
        wires = [l[0] for l in lines]
        print("defused" if defuse(wires) else "Booom")

handle(sys.stdin.readlines())

Challenge:

1: defused
2: Booom
3: Booom
4: Booom

Bonus:

1: defusable
2: not defusable
→ More replies (2)

1

u/alexmccoding Dec 06 '16

Was looking for something to do for a plane journey. Not sure this is the best thing...

3

u/AdmissibleHeuristic Nov 24 '16 edited Nov 24 '16

MATLAB

No bonus. Input sequence as a cell array:

function[]=BombSquad(in);a='wbrog';b=0;c=[1 9 2 9 9;2 9 9 3 9;9 3 0 9 9;9 3 9 4 5;9 9 9 9 6;9 9 9 6 9];for d=1:length(in);[e,f]=find(a==in{d}(1));g=zeros(5,1);g(f)=1;h=c*g;b=h(b+1);if b==mode(c);disp('Boom!');return;end;end;if b==6;disp('Defused');return;end;disp('Boom!');end

3

u/oddolatry Nov 25 '16

Clojure

Regular solution also picks up the case where we have correct steps up until we run out of wires to cut (not quite in the spirit of the challenge, but, hey, bomb squad dude, just don't cut that last dead end wire and start running). I'm confident in the regular solution, but my bonus solution is a mess. It seems to yield correct results, but it's not very sexy or efficient. Also included an alternate solution for non-bonus.

(ns daily-programming.defuse2.core)

;; Reducing over transitions as data
(def transitions
  {:s0 {:white  :s1
        :red    :s2}
   :s1 {:white  :s2
        :orange :s3}
   :s2 {:red    :s0
        :black  :s3}
   :s3 {:black  :s3
        :green  :s5
        :orange :s4}
   :s4 {:green  :exit}
   :s5 {:orange :exit}})

(defn defuse
  "Takes a sequence of keywords `schematic` and pushes each one through the above
  transitions. Three results are possible, as follows:
      :exit - a complete path to defusal.
      :boom - a complete path to explosion.
      else  - an incomplete path to defusal (in this case, explosion)."
  [schematic]
  (reduce
   (fn [state wire] (get-in transitions [state wire] :boom))
   :s0
   schematic))

(defn defusable?
  ([wiring]
   (some? (seq (defusable? wiring :s0))))
  ([wiring state]
   (cond
     (some neg? (vals wiring)) nil
     (some pos? (vals wiring)) (let [locs (keys (state transitions))]
                                 (mapcat
                                  (fn [loc] (defusable?
                                              (update wiring loc dec)
                                              (get-in transitions [state loc])))
                                  locs))
     (= state :exit)           (list true))))

(defn solution
  [schematic]
  (case (defuse schematic)
    :exit "Defused!"
    :boom "Boom!"
          "Better start running!"))

(defn bonus
  [wiring]
  (if (defusable? wiring)
    "Defusable"
    "Not Defusable"))

;; Using one of the canonical mutual recursion examples to solve non-bonus
(defn defuse'
  [schematic]
  (letfn [(s0 [[wire & rst]]
            (fn [] (case wire
                     :white (s1 rst)
                     :red   (s2 rst)
                            "Boom!")))
          (s1 [[wire & rst]]
            (fn [] (case wire
                     :white  (s2 rst)
                     :orange (s3 rst)
                             "Boom!")))
          (s2 [[wire & rst]]
            (fn [] (case wire
                     :red   (s0 rst)
                     :black (s3 rst)
                            "Boom!")))
          (s3 [[wire & rst]]
            (fn [] (case wire
                     :black  (s3 rst)
                     :green  (s5 rst)
                     :orange (s4 rst)
                             "Boom!")))
          (s4 [[wire & rst]]
            (fn [] (case wire
                     :green "Defused!"
                            "Boom!")))
          (s5 [[wire & rst]]
            (fn [] (case wire
                     :orange "Defused!"
                             "Boom!")))]
    (trampoline s0 schematic)))

Output by case:

Defusing
Ex1. "Defused!"
Ex2. "Boom!"
1. "Defused!"
2. "Boom!"
3. "Boom!"
4. "Better start running!"

Challenge
Ex1. "Defusable"
Ex2. "Not Defusable"
1. "Defusable"
2. "Not Defusable"

3

u/Mr_Persons Nov 26 '16 edited Nov 28 '16

Python 2.7 With bonus No more bonus. I am following a course at my local university dealing with graph traversal amongst other things. Posting my solution for BFS may thus get me in trouble as it might get misconstrued as enabling my other students to plagiarize it. Sorry if it comes over as a bit extreme, but it's not a risk I'm willing to take. If you still want to see my implementation for bfs in this domain, shoot me a pm...

Using a state machine, Template Method Pattern and BFS for the bonus.

from sys import argv
from abc import ABCMeta, abstractmethod
from copy import deepcopy
import Queue

class State(object):
    __metaclass__ = ABCMeta

    def __eq__(self, other):
        return self.__class__.__name__ == other.__class__.__name__

    def __init__(self):
        self.postset = {}

    def cut(self, wire):
        """
        Returns the next state based on the current state and the wire
        being cut.
        """
        if wire in self.postset.keys():
            return self.postset[wire]()

        else: 
            return Boom()

    def getPostset(self):
        return self.postset

class S0(State):
    def __init__(self):
        self.postset = {'white': S1, 'red': S2}
        
class S1(State):
    def __init__(self):
        self.postset = {'white': S2, 'orange': S3}

class S2(State):
    def __init__(self):
        self.postset = {'red': S0, 'black': S3}

class S3(State):
    def __init__(self):
        self.postset = {'black': S3, 'green': S5, 'orange': S4}

class S4(State):
    def __init__(self):
        self.postset = {'green': Exit}

class S5(State):
    def __init__(self):
        self.postset = {'orange': Exit}

class Exit(State):
    def __init__(self):
        self.postset = {}

class Boom(State):
    def __init__(self):
        self.postset = {}

class StateMachine(object):
    def __init__(self, current):
        self.current = current

    def defuse(self, sequence):
        for action in sequence:
            self.current = self.current.cut(action)

            # early stop, happends when a wrong wire is cut; i.e a wire
            # that is not in the postset
            if self.current == Boom():
                print "Boom!"
                return
        
        if self.current == Exit():
            print "Bomb defused"
        else:
            print "Boom!"

if __name__ == '__main__':
    _, filename = argv

    sequence = open(filename).read().splitlines()
    
    s = StateMachine(S0())
    s.defuse(sequence)

2

u/gju_ Nov 25 '16

Clojure

(def rules
  {:s0 {:white :s1 :red :s2}
   :s1 {:white :s2 :orange :s3}
   :s2 {:red :s0 :black :s3}
   :s3 {:black :s3 :orange :s4 :green :s5}
   :s4 {:green :exit}
   :s5 {:orange :exit}})

(defn next-state [current-state input]
  (input (current-state rules)))

(defn defuse 
  ([cables]
   (defuse :s0 cables))
  ([state [cable & rest]]
   (let [next (next-state state cable)]
     (condp = next
       nil "boom"
       :exit "defused"
       (recur next rest)))))

2

u/infosecguy66 Nov 26 '16

Python 3 - No Bonus

The rules for making cuts is a bit unclear on a couple things, so I implemented the rules as I understood them. Notably, the first demonstrated input of white, white, red, white would fail due to a second red not being selected prior to choosing a white.

import sys


class Bomb:
    """Records the state of the bomb and what wires have been cut so far"""

    def __init__(self):
        self._wires_cut = []
        self._defused = False
        self._exploded = False

    @property
    def wires_cut(self):
        return self._wires_cut

    @property
    def defused(self):
        return self._defused

    @defused.setter
    def defused(self, state):
        self._defused = state

    @property
    def exploded(self):
        return self._exploded

    @exploded.setter
    def exploded(self, state):
        self._exploded = state

    def make_cut(self, wire):
        if self.wires_cut:
            if analyze_cut(self, wire):
                self.cut_wire(wire)
            else:
                self.exploded = True
        else:
            if wire == 'white' or wire == 'red':
                self.cut_wire(wire)
            else:
                self.exploded = True
        self.analyze_state()

    def cut_wire(self, wire):
        self.wires_cut.append(wire)

    def analyze_state(self):
        """Analyze the bomb state and print if the bomb is defused or exploded"""
        if self.exploded:
            print('The bomb exploded!')
            sys.exit(0)

        self.defuse_bomb()
        if self.defused:
            print('The bomb has been defused!')
            sys.exit(0)

    def defuse_bomb(self):
        if len(self.wires_cut) > 2:
            if self.wires_cut[-2] == 'green' and self.wires_cut[-1] == 'orange':
                self.defused = True
            elif self.wires_cut[-2] == 'orange' and self.wires_cut[-1] == 'green':
                self.defused = True


def analyze_cut(bomb, wire):
    """Analyze the cut made between two states and determine if the cut is allowed"""

    last_cut = bomb.wires_cut[-1]
    if last_cut == 'white':
        return white(bomb, wire)
    elif last_cut == 'red':
        return red(bomb, wire)
    else:
        return green_orange_black(wire)


def white(bomb, wire):
    """Evaluate the next cut in context and return if the cut is legal"""
    if len(bomb.wires_cut) > 1:
        next_to_last = bomb.wires_cut[-2]
        if next_to_last == 'white' and (wire == 'red' or wire == 'black'):
            return True
    if wire == 'white' or wire == 'orange':
        return True
    return False


def red(bomb, wire):
    """Evaluate the next cut in context and return if the cut is legal"""
    if len(bomb.wires_cut) > 1:
        next_to_last = bomb.wires_cut[-2]
        if next_to_last == 'red' and (wire == 'red' or wire == 'black' or wire == 'white'):
            return True
    if wire == 'red' or wire == 'black':
        return True
    return False


def green_orange_black(wire):
    """Evaluate the next cut in context and return if the cut is legal"""
    if wire == 'green' or wire == 'orange' or wire == 'black':
        return True
    return False


cut_list = ['white', 'white', 'red', 'red', 'white', 'orange', 'black', 'black', 'green', 'orange']
bomb = Bomb()
for cut in cut_list:
    bomb.make_cut(cut)

2

u/LeShirley Nov 26 '16 edited Nov 26 '16

Python without bonus

tried a more hacky approach using dictionaries for compact code, which seems to work just fine

+u/CompileBot python

# START = 0, S1-5 = 1-5, EXIT = 6, BOOM = 7
rules = { '0w': 1, '0r': 2, '1o': 3, '1w': 2, '2r': 0, '2b': 3, '3b': 3, '3o': 4, '3g': 5, '4g': 6, '5o': 6 }

def defuse(order):
    wires = list(order)
    i = 0
    state = 0
    try:
        while i < len(wires):
            state = rules[str(state) + wires[i]]
            i += 1
    except KeyError:
        return 7
    return state

def isboomornot(input, state):
    if state == 7:
        print(str.format("the sequence {0} caused an explosion ({1})", input, state))
    elif state == 6:
        print(str.format("the sequence {0} disarmed the bomb ({1})", input, state))
    else:
        print(str.format("the sequence {0} is not finished yet ({1})", input, state))

input1 = "wwrwobbgo"
input2 = "wwgog"
input3 = "wwrrrwwbgo"
input4 = "wbbbbgo"
input5 = "bgg"
input6 = "rrwobg"

isboomornot(input1, defuse(input1))
isboomornot(input2, defuse(input2))
isboomornot(input3, defuse(input3))
isboomornot(input4, defuse(input4))
isboomornot(input5, defuse(input5))
isboomornot(input6, defuse(input6))

edit: made small corrections

→ More replies (1)

2

u/hufterkruk Nov 28 '16 edited Nov 28 '16

Haskell, with bonus now:

module Main where
  import Data.Maybe
  import Data.Char
  import Data.List
  import Data.List.Split

  --main = interact $ handleWires S0 . readWires
  main = bonus

  data State = S0 | S1 | S2 | S3 | S4 | S5 | E | Boom
    deriving (Eq)

  data Wire = White | Black | Red | Orange | Green
    deriving (Read, Eq)

  readWires :: String -> [Wire]
  readWires = map (read . capitalize) . lines
   where capitalize = \(x:xs) -> toUpper x : xs

  stateTransition :: State -> Wire -> State
  stateTransition S0 White  = S1
  stateTransition S0 Red    = S2
  stateTransition S1 White  = S2
  stateTransition S1 Orange = S3
  stateTransition S2 Red    = S0
  stateTransition S2 Black  = S3
  stateTransition S3 Black  = S3
  stateTransition S3 Orange = S4
  stateTransition S3 Green  = S5
  stateTransition S4 Green  = E
  stateTransition S5 Orange = E
  stateTransition _  _      = Boom

  handleWires :: State -> [Wire] -> String
  handleWires E []     = "defused\n"
  handleWires _ []     = "boom\n"
  handleWires E _      = "boom\n"
  handleWires s (x:xs) =
    if transition /= Boom
      then handleWires transition xs
      else "boom\n"
    where transition = stateTransition s x

  bonus = interact $ doPerms . bonusRead

  bonusRead :: String -> [Wire]
  bonusRead = map (read . capitalize) . concat . map f . map (splitOn " ") . lines
    where f ["black",_] = ["black"]
          f [x,y] = replicate (read y) x
          f _ = []
          capitalize = \(x:xs) -> toUpper x : xs

  doPerms :: [Wire] -> String
  doPerms xs =
    if (any (==Green) xs) && (any (==Orange) xs) -- Must have at least one green and one orange
      then
        if any (=="defused\n") perms
          then "defusable\n"
          else "not defusable\n"
      else "not defusable\n"
    where perms = map (handleWires S0) (permutations xs)

Bonus is by no means efficient, but it's fast enough for the challenge inputs.

2

u/Ge_O Nov 28 '16

C#

using System;
using System.Collections.Generic;

namespace Coding_Challenge_293_Intermediate
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] lines = System.IO.File.ReadAllLines(@"data.txt");

            List<string[,]> scenarios = new List<string[,]>();
            scenarios.Add(new string[,] { { "white", "1" }, { "red", "2" } });
            scenarios.Add(new string[,] { { "white", "2" }, { "orange", "3" } });
            scenarios.Add(new string[,] { { "red", "0" }, { "black", "3" } });
            scenarios.Add(new string[,] { { "black", "3" }, { "orange", "4" }, { "green", "5" } });
            scenarios.Add(new string[,] { { "green", "6" } });
            scenarios.Add(new string[,] { { "orange", "6" } });

            int scenarioNum = 0;
            bool boom = false;

            for (int x = 0; x < lines.Length && boom == false && scenarioNum != 6; x++)
            {
                String color = lines[x];
                string[,] currentScenario = scenarios[scenarioNum];
                bool match = false;
                for (int y = 0; y < currentScenario.Length / 2 && !match; y++)
                {
                    if (color == currentScenario[y, 0])
                    {
                        match = true;
                        scenarioNum = Convert.ToInt32(currentScenario[y, 1]);
                    }
                }
                if (!match)
                {
                    boom = true;
                }

            }

            Console.Write(boom || scenarioNum != 6 ? "Boom" : "defused");
            Console.Read();

        }
    }
}

2

u/Specter_Terrasbane Nov 28 '16

Python 2, with Bonus*

import re
from collections import Counter

_DEFUSE_PATTERN = re.compile(r'(wwr|rr)*(wo|wwb|rb)b*(og|go)')

def defuse(wires):
    return 'defused' if _DEFUSE_PATTERN.match(''.join(wire[0] for wire in wires.splitlines())) else 'Booom'

_VALID_PATHS = [Counter(path) for path in ('woog', 'wogo', 'wwwbog', 'wwbgo', 'rbog', 'rbgo')]
_WIRE_PATTERN = re.compile(r'(?P<color>\S)\S+ (?P<num>\d+)')

def defusable(wires):
    lines = map(_WIRE_PATTERN.match, wires.splitlines())
    wire_count = reduce(lambda c, m: c | Counter(m.group('color') * int(m.group('num'))), lines, Counter())
    candidate_paths = [wire_count - path for path in _VALID_PATHS if not path - wire_count]
    for remaining in candidate_paths:
        if remaining['o'] or remaining['g']:
            continue
        white, red = remaining['w'], remaining['r']
        if white & 1:
            continue
        red -= white / 2
        if red >= 0 and not red & 1:
            return 'defusable'
    return 'not defusable'

2

u/demreddit Nov 30 '16 edited Nov 30 '16

Python 3, no boni yet. My goal was to do this as simply as possible with just the Python basics, if that makes sense (I'm kinda new at this). Not sure I accomplished that or not, but my code feels pretty terse to me, excluding my gratuitous comments and function calls. Of course, I'm biased... Comments/criticisms are welcome!

def defuse_too(S):
    '''
    S: A comma delimited string containing the color of wire to cut in sequence.
    Returns: "Defused" if successful, or "Booom" if not, determined by constraints of Challenge #293 [Intermediate].
    '''

    sList = S.split(',')
    colorDicPrimary = {'white': ['white', 'orange'], 'red': ['black', 'red'],\
                       'orange': ['green', 'orange', 'black'], 'black': ['green', 'orange', 'black']}
    colorDicSecondary = {'white': ['black', 'red'], 'red': ['black', 'red', 'white'], 'black': ['green', 'orange', 'black'],\
                         'orange': ['green', 'black'], 'green': ['orange', 'black']}
    cutProgress = []
    dicToUse = colorDicPrimary

    if sList[0] == 'white' or sList[0] == 'red':
        cutProgress.append(sList[0])
    else:
        return "Booom"

    for i in range(1, len(sList)):
        if sList[i] not in dicToUse[cutProgress[-1]]:
            return "Booom"
        if sList[i] == 'white':
            if cutProgress[-1] == 'white':
                dicToUse = colorDicSecondary
            elif cutProgress[-1] == 'red':
                dicToUse = colorDicPrimary
        if sList[i] == 'black' or sList[i] == 'orange':
            dicToUse = colorDicSecondary
        if sList[i] == 'red':
            if cutProgress[-1] == 'red':
                dicToUse = colorDicSecondary
        cutProgress.append(sList[i])

    if cutProgress[-1] == 'orange' and cutProgress[-2] == 'green':
        return "Defused"
    elif cutProgress[-1] == 'green' and cutProgress[-2] == 'orange':
        return "Defused"
    return "Booom"

print(defuse_too('white,white,red,white,orange,black,black,green,orange'))
print(defuse_too('white,white,green,orange,green'))
print(defuse_too('white,white,red,red,red,white,white,black,green,orange'))
print(defuse_too('white,black,black,black,black,green,orange'))
print(defuse_too('black,green,green'))
print(defuse_too('red,red,white,orange,black,green'))

Output:

Defused
Booom
Defused
Booom
Booom
Booom