잊지 않겠습니다.

'코드도장'에 해당되는 글 4건

  1. 2009.01.07 0005. Jolly Jumper
  2. 2009.01.07 0004. Seven-Segment
  3. 2009.01.07 0003. The Trip
  4. 2009.01.07 0002. Minesweeper

0005. Jolly Jumper

시끌벅적 2009.01.07 12:02

require 'test/unit'

class JollyJumper
  attr_reader :values
 
  def initialize
    @values = []
  end
 
  def insert_value(value)
    @values << value
  end
 
  def print_values
    @values.each{ |value| print value.to_s + ' ' }
  end
 
  def calculate
    result = true
    @values.each_index do |index|
      first_value = (@values[index -1] - @values[index]).abs if @values[index-1] != nil
      second_value = (@values[index +1] - @values[index]).abs if @values[index+1] != nil   
      result &= values.member?(first_value) if first_value != nil
      result &= values.member?(second_value) if second_value != nil
    end
    result
  end 
end

class JollyJumperTest < Test::Unit::TestCase
  def test_case1
    jumper = JollyJumper.new
    assert_not_equal(nil, jumper)
    jumper.insert_value(4)
    jumper.insert_value(1)
    jumper.insert_value(4)
    jumper.insert_value(2)
    jumper.insert_value(3)   
    jumper.print_values()
    assert_equal(true, jumper.calculate)
  end
 
  def test_case2
    jumper = JollyJumper.new
    assert_not_equal(nil, jumper)
    jumper.insert_value(5)
    jumper.insert_value(1)
    jumper.insert_value(4)
    jumper.insert_value(2)
    jumper.insert_value(-1)   
    jumper.insert_value(6)   
    jumper.print_values()
    assert_equal(false, jumper.calculate)
  end
 
end

신고
Posted by xyzlast Y2K

import unittest
import os
import math

segment_enables = [
[True, True, True, False, True, True, True],
[False, False, True, False, False, True, False],
[True, False, True, True, True, False, True],
[True, False, True, True, False, True, True],
[False, True, True, True, False, True, False],
[True, True, False, True, False, True, True],
[False, True, False, True, True, True, True],
[True, True, True, False, False, True, True],
[True, True, True, True, True, True, True],
[True, True, True, True, False, True, True]
]


class SevenSegmentNumber:
    def __init__(self, number, size):
        self.size = size
        self.number = number
        self.max_line = size * 2 + 3
    
    def printHorizontalLine(self, print_enable):
        lines = ' '
        for i in range(self.size):
            if print_enable:
                lines = lines + '-'
            else:
                lines = lines + ' '
        lines = lines + ' '
        return lines
   
    def printVerticalLine(self, print_first, print_last):
        lines = ''
        vert_size = self.size  + 2
        if print_first:
            lines = lines + '|'
        else:
            lines = lines + ' '
       
        for i in range(vert_size - 2):
            lines = lines + ' '

        if print_last:
             lines = lines + '|'
        else:
             lines = lines + ' '       
        return lines  
   
   
    def getLine(self, line):
        total_line = self.size * 2 + 3
        line_segment = (total_line - 3) / 2 + 1
        line_end = total_line - 1       
        out_line = ''      
        if line == 0:
            out_line = self.printHorizontalLine(segment_enables[self.number][0])
        elif 0 < line and line < line_segment:
            out_line = self.printVerticalLine(segment_enables[self.number][1], segment_enables[self.number][2])
        elif line == line_segment:
            out_line = self.printHorizontalLine(segment_enables[self.number][3])
        elif line_segment < line and line < line_end:
            out_line = self.printVerticalLine(segment_enables[self.number][4], segment_enables[self.number][5])
        elif line == line_end:
            out_line = self.printHorizontalLine(segment_enables[self.number][6])
        return out_line

class Numbers:   
    def __init__(self):
        self.numbers = []
        self.seven_segments = []

    def displayNumber(self, number, size):
        decimal = int(math.log(number) / math.log(10)) + 1
        self.numbers = []
        self.seven_segments = []
       
        for i in range(decimal):
            self.numbers.append(int(str(number)[i]))
            segment = SevenSegmentNumber(self.numbers[i], size)
            self.seven_segments.append(segment)
       
        max_line = self.seven_segments[0].max_line
        for i in range(max_line):
            line = ''
            for s in range(decimal):
                line = line + self.seven_segments[s].getLine(i) + ' '
            print line
       

class SevenSegmentNumberTest(unittest.TestCase):
    """
    def testDisplay(self):
        print 'Start'
        zero = SevenSegmentNumber(8, 3)
       
        for i in range(zero.max_line):
            print zero.getLine(i),
            print ""
    """
    def testNumber1(self):
        number = SevenSegmentNumber(8, 2)
        #print number.getLine(0)
        #self.assertEqual(number.max_line, 3 + 2 * 2)
        #self.assertEqual('    ', number.getLine(0))
        #self.assertEqual('   |', number.getLine(1))
       
        #for i in range(0, number.max_line):
        #    print number.getLine(i)
   
    def testOutputNumber(self):
        for i in range(10):
            number = SevenSegmentNumber(i, 2)
            for j in range(number.max_line):
                print number.getLine(j)
      
if __name__ == '__main__':
    #unittest.main()
    n = Numbers()
    n.displayNumber(1238, 3)

  

require 'test/unit'

class SevenSegment
    attr_reader :number, :size, :height, :width
    attr_writer :number, :size
   
    @@segment_enables = [
            [true, true, true, false, true, true, true],
            [false, false, true, false, false, true, false],
            [true, false, true, true, true, false, true],
            [true, false, true, true, false, true, true],
            [false, true, true, true, false, true, false],
            [true, true, false, true, false, true, true],
            [false, true, false, true, true, true, true],
            [true, true, true, false, false, true, false],
            [true, true, true, true, true, true, true],
            [true, true, true, true, false, true, true] ]
   
    def initialize(number, size)
        @number = number
        @size = size
        @height = size * 2 + 3
        @width = size + 2
    end
   
    def get_vertical_line(mark_first, mark_second)
        line = ''
        length = @size + 2
        
        line = line + '|' if mark_first
        line = line + ' ' if !mark_first

        @size.times { line = line + ' ' }
       
        line = line + '|' if mark_second
        line = line + ' ' if !mark_second
        line       
    end
   
    def get_horizontal_line(enable)       
        mark = ''
        mark = '-' if enable
        mark = ' ' if !enable
        length = self.size + 2

        line = ' '
        @size.times { line = line + mark }
        line = line + ' '
        line
    end
    
    def get_line(line_count)
        if line_count == 0 then self.get_horizontal_line(@@segment_enables[@number][0])
        elsif line_count > 0 and line_count < (@size+1) then self.get_vertical_line(@@segment_enables[@number][1], @@segment_enables[@number][2])
        elsif line_count == (@size+1) then self.get_horizontal_line(@@segment_enables[@number][3])
        elsif line_count > (@size+1) and line_count < (@size * 2 + 2) then self.get_vertical_line(@@segment_enables[@number][4], @@segment_enables[@number][5])           
        elsif line_count == (@size * 2 + 2) then self.get_horizontal_line(@@segment_enables[@number][6])                   
        end
    end   
end

class SevenSegments
    attr_reader :numbers, :size
    attr_writer :numbers, :size
   
    def initialize(size, number)
        @size = size
        self.set_number(number)
    end

    def set_number(number)
        @numbers = []
        string_numbers = number.to_s()
        string_numbers.length.times { |index| @numbers << string_numbers[index] - 48 }
    end

    def display_number
        puts ' '
        seven_segments = []
        @numbers.each { |n| seven_segments << SevenSegment.new(n, @size) }
        line = @size * 2 + 3

        line.times do |line_count|
            line = ''
            seven_segments.each do |seven_segment|
                line = line + seven_segment.get_line(line_count) + ' '
            end
            puts line
        end
       
    end
end

class SevenSegmentsTest < Test::Unit::TestCase
    def test_numbers
        s = SevenSegments.new(3, 987654321)
        print s.numbers[0]       
        s.display_number
        assert_equal(9, s.numbers[0])
    end
end

class SevenSegmentTest < Test::Unit::TestCase
    def test_number0
        s = SevenSegment.new(0,2)
        assert_equal(" -- ", s.get_line(0))
        assert_equal("|  |", s.get_line(1))
        assert_equal("|  |", s.get_line(2))
        assert_equal("    ", s.get_line(3))
        assert_equal("|  |", s.get_line(4))
        assert_equal("|  |", s.get_line(5))
        assert_equal(" -- ", s.get_line(6))
    end

    def test_number1
        s = SevenSegment.new(1,2)
        assert_equal("    ", s.get_line(0))
        assert_equal("   |", s.get_line(1))
        assert_equal("   |", s.get_line(2))
        assert_equal("    ", s.get_line(3))
        assert_equal("   |", s.get_line(4))
        assert_equal("   |", s.get_line(5))
        assert_equal("    ", s.get_line(6))
    end
    
    def test_number8
        s = SevenSegment.new(8,2)
        assert_equal(" -- ", s.get_line(0))
        assert_equal("|  |", s.get_line(1))
        assert_equal("|  |", s.get_line(2))
        assert_equal(" -- ", s.get_line(3))
        assert_equal("|  |", s.get_line(4))
        assert_equal("|  |", s.get_line(5))
        assert_equal(" -- ", s.get_line(6))
       
    end
end

신고
Posted by xyzlast Y2K

0003. The Trip

시끌벅적 2009.01.07 11:59
import unittest

class TheTrip:
    def __init__(self, count):
        self.count = count
        self.costs = []
        pass
    def inputCost(self, cost):
        self.costs.append( float(cost * 100) )
    def calculateAverageCost(self):
        return float( sum(self.costs) / len(self.costs) ) / 100.00
    def calculateMinCharge(self):
        average = self.calculateAverageCost() * 100.00
        diff_values = []
        for value in self.costs:
            differ = average - value
            diff_values.append(abs(differ))
        return sum(diff_values) / 2.00 / 100.00

class TheTripTest(unittest.TestCase):
    def setUp(self):
        pass
    def testInsertValue(self):
        t = TheTrip(3)
        t.inputCost(10.00)
        t.inputCost(20.00)
        t.inputCost(30.00)
        self.assertEqual(20.00, t.calculateAverageCost())
        self.assertEqual(10.00, t.calculateMinCharge())
    def testInsertValue2(self):
        t = TheTrip(4)
        t.inputCost(15.00)
        t.inputCost(15.01)
        t.inputCost(3.00)
        t.inputCost(3.01)
        self.assertEqual(11.99, t.calculateMinCharge())
if __name__ == '__main__':
    unittest.main()


require 'test/unit'

class TheTrip
attr_reader :member, :costs, :average
attr_writer :member, :costs

    def initialize(number)
        self.member = number
        self.costs = []
    end

    def input_cost(cost)
        self.costs << cost
        @average = 0
        self.costs.each {|value| @average += value }
        @average /= self.costs.length
    end

    def get_min_charge()
        charges = 0.00
        self.costs.each { |value| charges += (value - self.average).abs }
        return charges / 2.00
    end
    
end

class TheTripTest < Test::Unit::TestCase
    def test_case1
        t = TheTrip.new(3)
        t.input_cost(10.00)
        t.input_cost(20.00)
        t.input_cost(30.00)
        assert_equal(20.00, t.average)
        assert_equal(10.00, t.get_min_charge())
    end

    def test_case2
        t = TheTrip.new(4)
        t.input_cost(15.00)
        t.input_cost(15.01)
        t.input_cost(3.00)
        t.input_cost(3.01)
        assert_equal(11.99, t.get_min_charge())
    end
end
신고
Posted by xyzlast Y2K

0002. Minesweeper

시끌벅적 2009.01.07 11:59

import os
import unittest


class Minesweeper:
    def __init__(self):
        self.rows = []
        pass
   
    def clearRow(self):
        self.rows = []
   
    def insertRow(self, row):
        self.rows.append(row)
   
    def printArray2D(self, array_2d):
        for row in array_2d:
            for item in row:
                print item,
            print
   
    def printMine(self):
        self.printArray2D(self.rows)
   
    def initLocation(self):
        mine_locations = []
        for row in self.rows:
            row_locations = []
            for item in row:
                row_locations.append(0)
            mine_locations.append(row_locations)
        self.mine_locations = mine_locations
   
    def isInRange(self, row_location, col_location):
        if row_location >= 0 and col_location >= 0 and row_location < len(self.rows) and col_location < len(self.rows[0]):
            return True
        else:
            return False
       
    def getMineLocation(self):
        self.initLocation()       
        row_location = 0
        for row in self.rows:
            col_location = 0
            for item in row:
                if item == '*':
                    self.mine_locations[row_location][col_location] = '*'
                    for row_index in [-1, 0, 1]:
                        for col_index in [-1, 0, 1]:
                            if self.isInRange(row_location + row_index, col_location + col_index) and self.mine_locations[row_location + row_index][col_location + col_index] != '*':
                                self.mine_locations[row_location + row_index][col_location + col_index] += 1
                col_location += 1
            row_location += 1
   
    def printMineLocation(self):
        self.printArray2D(self.mine_locations)
   
class MinesweeperTest(unittest.TestCase):
    def setUp(self):
        pass
    def testCheckValue(self):
        m = Minesweeper()
        m.insertRow(['.','.','*','.'])
        m.insertRow(['.','*','.','.'])
        m.printMine()
       
        self.assertEqual(m.isInRange(0,0), True)
        self.assertEqual(m.isInRange(5,0), False)
        self.assertEqual(m.isInRange(1,0), True)
        self.assertEqual(m.isInRange(0,5), False)
       
        m.getMineLocation()
        m.printMineLocation()
   
    def testCheckMine2(self):
        m = Minesweeper()
        m.insertRow(['*', '*', '.', '.', '.'])
        m.insertRow(['.', '.','.','.','.'])
        #m.insertRow(['.', '.','.','.','.'])
        m.insertRow(['.', '*','.','.','.'])

        m.getMineLocation()
        m.printMineLocation()
        self.assertEqual(True, True)
    #def tearDown(self):
    #    pass

if __name__ == '__main__':
    unittest.main()

  

require 'test/unit'

class Minesweeper
    attr_reader :rows, :calc_locations
    attr_writer :rows, :calc_locations
   
    def initialize
        self.rows = []
        self.calc_locations = []
    end
   
    def print_rows
        @rows.length.times do |row_index|
            @rows[row_index].length.times {|col_index| print @rows[row_index][col_index].to_s() + ' ' }  
            puts ' '
        end
    end

    def calc_rows
        self.calc_locations = []
        rows.length.times do |row_index|
            row = []
            rows[row_index].length.times do |col_index|
               if rows[row_index][col_index] != '*' : row.push(0)
               else  row.push('*')
               end
            end
            @calc_locations.push(row)
        end

        @rows.length.times do |row_index|
            @rows[row_index].length.times do |col_index|
                -1.upto(1) { |i| -1.upto(1) { |j| @calc_locations[i+row_index][j+col_index] += 1 if self.is_in_range(i+row_index,j+col_index) } } if @rows[row_index][col_index] == '*'
            end
        end
    end

    def is_in_range(row_index, col_index)
        return false if row_index < 0
        return false if col_index < 0
        return false if row_index >= @calc_locations.length
        return false if col_index >= @calc_locations[row_index].length
        return false if @rows[row_index][col_index] == '*'
        return true       
    end

    def print_calc_rows
        @calc_locations.length.times do |row_index|
            @calc_locations[row_index].length.times {|col_index| print @calc_locations[row_index][col_index].to_s() + ' ' }  
            puts ' '
        end
    end   
end

class MinesweeperTest < Test::Unit::TestCase
    def test_case1
        mine = Minesweeper.new()
        mine.rows.push(['.', '*', '.', '.', '*'])
        mine.rows.push(['.', '.', '*', '.', '.'])
        mine.rows.push(['.', '.', '*', '.', '.'])
        mine.rows.push(['.', '.', '*', '.', '.'])
        mine.print_rows()
        mine.calc_rows()
        mine.print_calc_rows()
        assert_equal(1, 1)

        assert_equal(true, mine.is_in_range(0,0))
        assert_equal(false, mine.is_in_range(6, 0))
        assert_equal(false, mine.is_in_range(0, 1))
        assert_equal(1, mine.calc_locations[0][0])
        assert_equal(2, mine.calc_locations[0][2])
    end
end

신고
Posted by xyzlast Y2K


티스토리 툴바