Task: Flipping bits game




Go: package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {

	rand.Seed(time.Now().UnixNano())
    
	var n int = 3 
	var moves int = 0
	
	a := make([][]int, n)
	for i := range a {
		a[i] = make([]int, n)
		for j := range a {
			a[i][j] = rand.Intn(2)
		}
	}

    b := make([][]int, len(a))
	for i := range a {
		b[i] = make([]int, len(a[i]))
		copy(b[i], a[i])
	}
	
	for i := rand.Intn(100); i > 0 || compareSlices(a, b) == true; i-- {
		b = flipCol(b, rand.Intn(n) + 1)
		b = flipRow(b, rand.Intn(n) + 1)
	}
	
	fmt.Println("Target:")
	drawBoard(a)
	fmt.Println("\nBoard:")
	drawBoard(b)
	
	var rc rune
	var num int
	
	for {
		for{
			fmt.Printf("\nFlip row (r) or column (c)  1 .. %d (c1, ...): ", n)
			_, err := fmt.Scanf("%c%d", &rc, &num)
			if err != nil {
				fmt.Println(err)
				continue
			}
			if num < 1 || num > n {
				fmt.Println("Wrong command!")
				continue
			}
			break
		}
		
		switch rc {
			case 'c':
				fmt.Printf("Column %v will be flipped\n", num)
				flipCol(b, num)
			case 'r':
				fmt.Printf("Row %v will be flipped\n", num)
				flipRow(b, num)
			default:
				fmt.Println("Wrong command!")
				continue
		}
		
		moves++
		fmt.Println("\nMoves taken: ", moves)
		
		fmt.Println("Target:")
		drawBoard(a)
		fmt.Println("\nBoard:")
		drawBoard(b)
	
		if compareSlices(a, b) {
			fmt.Printf("Finished. You win with %d moves!\n", moves)
			break
		}
	}
}

func drawBoard (m [][]int) {
	fmt.Print("   ")
	for i := range m {
		fmt.Printf("%d ", i+1)	
	}
	for i := range m {
		fmt.Println()
		fmt.Printf("%d ", i+1)
		for _, val := range m[i] {
			fmt.Printf(" %d", val)
		}
	}
	fmt.Print("\n")
}

func flipRow(m [][]int, row int) ([][]int) {
	for j := range m {
		m[row-1][j] ^= 1
	}
	return m
}
 
func flipCol(m [][]int, col int) ([][]int) {
	for j := range m {
		m[j][col-1] ^= 1
	}
	return m
}

func compareSlices(m [][]int, n[][]int) bool {
	o := true
	for i := range m {
		for j := range m {
			if m[i][j] != n[i][j] { o = false }
		}
	}
	return o 
}




Python: 

from random import randrange
from copy import deepcopy
from string import ascii_lowercase


try:    
    input = raw_input
except:
    pass

N = 3   

board  = [[0]* N for i in range(N)]

def setbits(board, count=1):
    for i in range(count):
        board[randrange(N)][randrange(N)] ^= 1

def shuffle(board, count=1):
    for i in range(count):
        if randrange(0, 2):
            fliprow(randrange(N))
        else:
            flipcol(randrange(N))


def pr(board, comment=''):
    print(str(comment))
    print('     ' + ' '.join(ascii_lowercase[i] for i in range(N)))
    print('  ' + '\n  '.join(' '.join(['%2s' % j] + [str(i) for i in line])
                             for j, line in enumerate(board, 1)))

def init(board):
    setbits(board, count=randrange(N)+1)
    target = deepcopy(board)
    while board == target:
        shuffle(board, count=2 * N)
    prompt = '  X, T, or 1-%i / %s-%s to flip: ' % (N, ascii_lowercase[0], 
                                                    ascii_lowercase[N-1])
    return target, prompt

def fliprow(i):
    board[i-1][:] = [x ^ 1 for x in board[i-1] ]
    
def flipcol(i):
    for row in board:
        row[i] ^= 1

if __name__ == '__main__':
    print(__doc__ % (N, N))
    target, prompt = init(board)
    pr(target, 'Target configuration is:')
    print('')
    turns = 0
    while board != target:
        turns += 1
        pr(board, '%i:' % turns)
        ans = input(prompt).strip()
        if (len(ans) == 1 
            and ans in ascii_lowercase and ascii_lowercase.index(ans) < N):
            flipcol(ascii_lowercase.index(ans))
        elif ans and all(ch in '0123456789' for ch in ans) and 1 <= int(ans) <= N:
            fliprow(int(ans))
        elif ans == 'T':
            pr(target, 'Target configuration is:')
            turns -= 1
        elif ans == 'X':
            break
        else:
            print("  I don't understand %r... Try again. "
                  "(X to exit or T to show target)\n" % ans[:9])
            turns -= 1
    else:
        print('\nWell done!\nBye.')