ธันวาคม 22, 2559

Insertion Sort

slide : InsertionSort.pdf

        Insertion Sort (การเรียงลำดับแบบแทรก) เป็นขั้นตอนวิธีการเรียงลำดับอย่างง่าย ทำงานโดยจะแบ่งข้อมูลในรายการเป็นสองส่วนคือส่วนที่เรียงแล้ว และส่วนที่ยังไม่เรียง แน่นอนว่าในตอนเริ่มแรกส่วนที่เรียงแล้วก็จะมีอย่างน้อยหนึ่งตัว และจะเริ่มหยิบข้อมูลตัวหนึ่งของส่วนที่ยังไม่เรียงมาเปรียบเทียบเพื่อหาตำแหน่งที่เหมาะสมในการแทรกลงในข้อมูลที่เรียงแล้ว ลักษณะเดียวกับการเรียงไพ่ในมือ และด้วยประสิทธิภาพ O(n^2) ดังนั้นการเรียงลำดับแบบแทรกจึงไม่เหมาะในการทำงานในรายการที่มีจำนวนสมาชิกมากๆ (อ้างอิงจาก https://th.wikipedia.org/wiki/การเรียงลำดับแบบแทรก)

Text Mode


        เริ่มต้นด้วยการเขียนโปรแกรม Insertion Sort ด้วยภาษา python ดังนี้

                                           

        และผลที่ได้

                                       

        จากนั้นได้เพิ่มการแสดงผลแต่ละขึ้นตอน และจัดเรียง code ใหม่

                                                 

        ได้ผลดังนี้

                                        

Sort with GUI [เพิ่มเติมใน slide]


        ได้ทำการดัดแปลง code จาก Selection Sort ให้ใช้วิธี sort แบบ Insertion Sort แทน และทำการปรับเปลี่ยนการแสดงผลให้เหมาะสมกับ Insertion Sort

                                         

        การทำงานของโปรแกรม
        - เริ่มการทำงานเมื่อ ใส่ input และกดปุ่ม " sort! " ที่มุมขวา-บน ในโปรแกรมจะทำการ sort ด้วยวิธี Insertion Sort และเก็บข้อมูลการ Sort ของทุกขั้นตอนไว้ และเริ่มสร้าง widgets ที่มีข้อมูลจาก input อยู่ภายใน

                                         

        - จะแสดงผลการ sort ขั้นต่อไปเมื่อกดปุ่ม "next" ที่มุมขวา-ล่าง (สามารถกดย้อนดูขั้นตอนที่ผ่านมาแล้วด้วยปุ่ม "previous") 

                                         
                                         

ปล. การ sort แบบเต็ม สามารถดูได้จาก slide บนโพสต์

พฤศจิกายน 27, 2559

Selecting Sort

slide present #1 : Quiz3.pdf (slide เดียวกับ Simple Calculator)
slide present #2 : Selection Sort.pdf

1st week : 

        ศุกร์ ที่ 11 พฤศจิกายน 2559
                - ได้เริ่มทำ Selection Sort ใน python โดยแสดงผลใน terminal
                - มีการ commit ลง bitbucket 4 ครั้ง
                - ดูรายละเอียด code และผลลัพธ์ ที่ slide present #1 (ด้านบนโพสต์) 

2nd week :

        พุธ ที่ 11 พฤศจิการยน 2559
                - present เรื่อง Selection Sort และ Simple Calculator

        ศุกร์ ที่ 18 พฤศจิกายน 2559
                - สร้าง app ด้วย kivy จากโค๊ด Selection Sort ใน python


นี่คือ code จากทั้ง 2 ไฟล์ คือ ไฟล์ .kv และ .py ตามลำดับ

                การสร้าง GUI จะสร้างจาก BoxLayout ทั้งหมด ทั้งในส่วนหลัก และส่วนย่อย (เนื่องจากง่ายในการใช้งาน) โดยส่วนหลักจะตั้ง orientation เป็นแบบ vertical (แนวตั้ง) หลังจากนั้นจึงสร้าง ส่วนย่อย
                - ส่วนย่อยแรก ได้สร้างเป็น BoxLayout แบบ horizontal (แนวนอน) ซึ่งเป็น Default  เพื่อสร้าง Label แสดงคำว่า 'input' และสร้าง TextInput ไว้รับค่าที่จะนำมา Sort
                - ส่วนย่อยที่สอง สร้างเป็น BoxLayout เช่นกัน ซึ่งจะสร้าง Button ไว้ ซึ่ง binding กับ method selectionSort( ) และสร้าง Label แสดงผลลัพธ์หลังจากการ Sort

                การทำงานของโปรแกรม
                - เริ่มด้วยการกำหนด Default ของ dSorted (data อาจไม่จำเป็นต้องมี Default) เพื่อนำไปแสดงเป็นผลลัพธ์ของโปรแกรมก่อน
                - เมื่อได้รับ input จาก TextInput แล้วกดปุ่ม ' sort! ' โปรแกรมจะเรียกใช้ selectionSort( ) รับค่า จาก TextInput มาใส่ไว้ใน self.data จากนั้นจึงเริ่มการ sort (เป็นการเปรียบเทียบ String ทุกตัว ที่นำมาใส่ใน input) แล้วจึงนำผลลัพธ์ จากการ Sort ส่งค่าไปให้ .kv แสดงผล

                                         
โปรแกรม หลังจากการ Sort

3rd week :

        พุธ ที่ 23 พฤศจิกายน 2559
                - ปรับเปลี่ยนหน้าตา GUI
                - เพิ่มการแสดงผลจากการ Sort ทุกๆขั้นตอนด้วย clock
                - เปลี่ยนรูปแบบการรับ input โดยแบ่งด้วย comma ( , )

                                      
                                     

                จาก code ข้างต้นจะเห็นว่ามีการรับ data จาก input มา โดยทำการ split ด้วย ' , ' ทำให้สามารถ Sort ค่าที่มากกว่า 1 หลักได้ นอกจากนั้นยังมีการใช้ clock ในการเรียกใช้ method update ทุกๆ 1 วินาที โดย method นี้จะส่งค่าของ keepSorted ให้ .kv ไปแสดงผล ซึ่งค่าของ keepSorted ได้จากค่าหนึ่งใน list ของ self.keep ซึ่ง list นี้ได้มาจาก...

                                     
                ทำให้โปรแกรมต้องเปลี่ยนหน้าตา ดังนี้

                                         
                                           
                                         

                และมีการ update ค่าเรื่อยๆ จนกลายเป็นค่าที่ Sort เสร็จเรียบร้อยดีแล้ว


        ศุกร์ ที่ 25 พฤศจิการยน 2559
                - ปรับเปลี่ยนหน้าตา GUI
                - เปลี่ยนการแสดงผลจากแบบ text เป็นกล่องตัวเลข
                - เลิกใช้ clock แต่จะแสดงผลเป็น step by step (กด 1 ครั้ง เปลี่ยนไป 1 ขั้นตอน)
                - กดเพื่อเปลี่ยนไปขั้นถัดไปได้ และกดเพื่อย้อนหลังกลับไปขั้นก่อนหน้าได้
                - ดูรายละเอียดเพิ่มเติมที่ slide present #2 (ด้านบนโพสต์)

                                         

                GUI ทุกส่วนจะเป็น BoxLayout ยกเว้นส่วนแสดงการ Sort เนื่องจากหาก ใช้ BoxLayout จะทำให้ data ที่แสดงจะเรียงเป็นแถวเดียว (มีข้อดีที่จะทำให้ดูการเรียงของ data ง่าย) จึงมีข้อเสีย คือเมื่อรับ data ที่จะนำมา Sort เยอะๆ จะทำให้ผลออกมาไม่สวย (เป็นกล่องสูงๆ ที่ไม่มีความกว้าง) และอาจทำให้มองดูตัวเลขลำบาก เพราะความกว้างกล่องน้อย และทำให้โดนกล่องถัดไปบังตัวเลข [ภาพเพิ่มเติม ใน slide present #2]

                การทำงานของโปรแกรม
                - จะเริ่มการ Sort เมื่อใส่ input และกดปุ่ม ' sort! ' ทางขวา-บน แล้วโปรแกรมจะเริ่มสร้างตัวแปร และเก็บค่าของทุกขั้นตอนของการ Sort ไว้ จากนั้นจึงสร้าง widget ขึ้นมาเป็นกล่อง (Button) ที่มีตัวเลขอยู่ภายใน ซึ่งเป็นตัวเลขเริ่มต้น [code ใน slide present #2]

                                          

                - จะแสดงค่าในขั้นตอนถัดไป เมื่อกดปุ่ม 'next' ทางขวา-ล่าง และสามารถย้อนหลังได้ เมื่อกดปุ่ม 'previous' ทางซ้าย-ล่าง ทั้งสองปุ่มนั้นมีการ binding ไปยัง method เพื่อ clear widgets และสร้าง widget ขึ้นมาใหม่ โดยเมื่อกด next โปรแกรมจะเพิ่มค่า index เพื่อจะใช้ป้อนให้ keep (list ที่เก็บ data ทุกขั้นตอนของการ Sort เอาไว้) แสดงค่าที่ต้องการออกมา ในทำนองเดียวกับ previous ที่จะลดค่า index ลง และป้อนให้ keep [ดู code ได้จาก slide present #2]

                                          

                - สีของกล่อง ก็อยู่ในขั้นตอนการสร้างปุ่มเช่นกัน โดยโปรแกรมจะมี list ที่เก็บค่า iMin ไว้, มี count_up (index ที่ส่งให้ keep นำค่าที่ต้องการออกมา) เมื่อมีตัวแปรเหล่านี้แล้ว จึงเอาไปใช้เป็นเงื่อนไขในการใส่สีของกล่อง [รายละเอียดเพิ่มเติมใน slide present #2]
                เช่น จากภาพด้านบน count_up = 1 (Sort ไปแล้ว 1 ขั้นตอน) 
                       กล่องที่ index น้อยกว่า count_up จะมีสีเขียว หรือก็คือ กล่องที่ 0 มีสีเขียว
                       กล่องที่ index เท่ากับ count_up จะมีสีแดง หรือก็คือ กล่องที่ 1 มีสีแดง
                       กล่องที่ index เท่ากับ imin[count_up] จะมีสีน้ำเงิน (ตาม list ที่เก็บค่าไว้ ซึ่งใน ต.ย. คือ กล่องที่ 4 จะมีสีน้ำเงิน)

Quiz3 : Simple Calculator

slide นำเสนอ : Quiz3.pdf  (รวม selection sort เล็กน้อย)

Programme Interface

การใช้งาน (use case)

        - คำนวณเลข 2 จำนวนง่ายๆ ได้ (บวก, ลบ, คูณ, หาร)

                1. ใส่ Input ซึ่งมี 3 ส่วนคือ ส่วนแรก ใส่ตัวตั้ง, ส่วนที่สอง กดปุ่มเพื่อเลือกเครื่องหมาย, ส่วนที่สาม ใส่ตัวบวก,ลบ,คุณ หรือ ตัวหาร
                2. กดที่ปุ่มที่มีเครื่องหมาย ' = '
                3. ผลลัพธ์จะแสดงอยู่ในช่องล่างสุด
 

        ในส่วน code

        

        ในส่วนนี้จะเป็นการสร้างช่องใส่ input ใน kv ด้วย class ที่มากับ kivy ที่ชื่อ TextInput มารับตัวเลขที่จะนำมาคำนวณ

                     

        ในส่วนนี้ใช้เป็นปุ่มที่จะรับค่าเครื่องหมาย (operator) โดยมีการ binding เมื่อ release ปุ่ม จะไปเรียกใช้ method จากไฟล์ .py เพื่อไปกำหนดค่าของเครื่องหมายตาม ปุ่มที่ถูกกด


        หลังจากได้รับ input ที่ต้องการทั้ง 3 แล้ว เมื่อผู้ใช้กดปุ่ม '=' แล้ว โปรแกรมก็จะเรียกใช้ method calculate( ) เพื่อเริ่มการคำนวณ เมื่อคำนวณเสร็จ ใน code บรรทัดสุดท้ายจะส่งค่าผลลัพธ์จะส่งค่าไปให้ทางส่วน .kv แสดงผลต่อไป
        โดยใน code การคำนวณนั้น เราไม่สามารถที่จะนำค่าที่นำมาจาก TextInput มาคำนวณทันทีเลยได้ เพราะค่าที่ได้รับมานั้นเป็น String ดังนั้นก่อนที่จะนำค่ามาคำนวณ จึงต้องเปลี่ยนค่าจะ String เป็นค่าตัวเลขที่สามารถคำนวณได้ ก็คือ int( ) หรือ float( ) แต่เนื่องจากใน use case ถัดไป int นั้นไม่สามารถที่จะ support ได้ ดังนั้นการคำนวณนี้จึงใช้ float( ) 

        - นำผลลัพธ์ที่ได้จากการคำนวณครั้งที่แล้วมาคำนวณต่อ (เป็นตัวตั้งของการคำนวณใหม่)

                1. หลังจากทำการคำนวณครั้งแรก หรือหลายครั้งไปแล้ว
                2. กดปุ่มที่แสดงผลลัพธ์ (ล่างสุด)
                3. ผลลัพธ์จากการคำนวณครั้งล่าสุด จะไปแทนที่ตัวตั้ง และรอการป้อน Input ที่เหลืออีก 2 ส่วน เพื่อใช้ไปการคำนวณต่อไป 

        ในส่วน code


        ทำการ binding ปุ่มที่แสดงผลลัพธ์ กับ method reCal( ) ซึ่งจะทำการกำหนดค่าของการคำนวณใหม่ให้ผู้ใช้ โดยจะนำค่าผลลัพธ์ครั้งล่าสุด ไปใส่แทน input1 หรือก็คือ ตัวตั้ง และกำหนดให้ input ตัวที่สอง และเครื่องหมายกลับไปเป็น default (ไม่มีค่า และกำลังหาใส่ค่า เพื่อนำไปคำนวณต่อ) จากนั้นจึง update ค่าไปให้ .kv แสดงผล ในบรรทัดสุดท้าย

ตุลาคม 18, 2559

Quiz2 : comiccreator

1. เปลี่ยนชื่อ method : on_children เป็น on_30september

           - เริ่มจากแก้ไขตามโจทย์

            - แล้วไปเพิ่มคำสั่ง on_30september ให้ถูกเรียกใช้ตามจุดต่างๆ


2. แสดงจำนวน StickMan บน statusbar

            - เพิ่ม text ที่ statusbar ด้านล่าง และเพิ่มตัวแปร smCount


           - เพิ่มการกำหนดค่าจาก drawingSpace ไปให้ statusbar หาก children = 0
           - เพิ่มการอัพเดทค่าของ smCount




           -  import : StickMan จาก comicwidgets
           - ทำการตรวจสอบชนิดของ children ใน remove หากเป็น StickMan ให้ลดจำนวน StickMan ลง 1 (sm_decrease)

            - เพิ่มการเรียกใช้ sm_increase ใน class: ToolStickman , Method: draw


3. การ remove แบบ Group
           - แยกกรณี การ remove (แบบ group / แบบไม่ group)

พฤศจิกายน 28, 2558

ปัญหา Raspberry Pi

1. รัน AS1 ได้ แต่รับค่า mouseX, mouseY เพี้ยนไป
2. การรันโปรแกรมค่อนข้างช้า
3. การต่อ wifi ไม่เสถียร

พฤศจิกายน 22, 2558

Lab Raspberry Pi

class Student:
    def __init__(self,name,Id,score):
        self.name = name
        self.id = Id
        self.score = score
    def get_name(self):
        return self.name
    def get_id(self):
        return self.id
    def get_score(self):
        return self.score
 
def setup():
    a = Student('Nay',1,50)
    b = Student('Tiny',2,70)
    c = Student('Kunkka',3,95)
    d = Student('Lina',4,79)
    e = Student('Balana',5,65)
    data = [a,b,c,d,e]
    display_data(data)
    count_grade(data)
    show_grade(data,3)
 
def count_grade(data):
    index = 0
    count = [0,0,0,0,0]
    text_temp = ['A','B','C','D','F']
    while(index < len(data)):
        if(data[index].get_score() > 80):
            count[0] += 1
        elif(data[index].get_score() > 70):
            count[1] += 1
        elif(data[index].get_score() > 60):
            count[2] += 1
        elif(data[index].get_score() > 50):
            count[3] += 1
        else:
            count[4] += 1
        index += 1  
    print('-----total grade-----')
    index = 0
    while(index < len(count)):
        print(text_temp[index],':',count[index],end = '   ')
        index += 1
    print()

def display_data(data):
    index = 0
    while(index < len(data)):
        print('---',index+1,'---')
        print('Name : ',data[index].get_name())
        print('ID : ',data[index].get_id())
        print('Score : ',data[index].get_score())
        grade_cal(data,index)
        print()
        index += 1

def grade_cal(data,index):
    print('Grade : ',end = '')
    if(data[index].get_score() > 80):
        print('A')
    elif(data[index].get_score() > 70):
        print('B')
    elif(data[index].get_score() > 60):
        print('C')
    elif(data[index].get_score() > 50):
        print('D')
    else:
        print('F')

def show_grade(data,Id):
    index = 0
    foundStudent = False  
    while(index < len(data) and not(foundStudent)):      
        if(data[index].get_id() == Id):
            foundStudent = True
        index += 1
    index -= 1  
    if(data[index].get_score() > 80):
        grade = 'A'
    elif(data[index].get_score() > 70):
        grade = 'B'
    elif(data[index].get_score() > 60):
        grade = 'C'
    elif(data[index].get_score() > 50):
        grade = 'D'
    else:
        grade = 'F'    
    print('---Grade Result---')
    print('name : ',data[index].get_name() )
    print('score : ',data[index].get_score())
    print('Grade : ',grade)

setup()

ตุลาคม 04, 2558

Lab5_strings

def setup():
   print(my_count("Thailand","a"))
   print(my_find("Thailand","i"))
   print(my_replace("Thailand","land","thai"))
   print(my_strip("Thailand     "))
   print(my_startswith("Thailand","Sun"))
   print(my_endswith("Thailand","and"))
 
def my_count(full,part):
   count = 0
   i = 0
   while(i<len(full)):
      if(full[i] == part):
         count = count+1
      i = i+1
   return count

def my_find(full,part):
   i = 0
   while(i<len(full)):
      if(full[i] == part):
         index = i
         break
      i = i+1
   return index

def my_replace(full,old,new):
   newStr = ""
   l = len(old)
   i = 0
   while(i<len(full)):
      a = full[i]
      j = 1
      while(j<l and i+j<len(full)):
         a = a+full[i+j]
         j = j+1
      if(a == old):
         newStr = newStr+new
         i = i+(l-1)
      else:
         newStr = newStr+full[i]
      i = i+1
   return newStr

def my_strip(full):
   newStr = ""
   i = 0
   while(i<len(full)):
      if(full[i] != ' '):
         start = i
         break
      i = i+1
   i = len(full)-1
   while(i>=0):
      if(full[i] != ' '):
         end = i
         break
      i = i-1
   j = start
   while(j<=end):
      newStr = newStr+full[j]
      j = j+1
   return newStr
 
def my_startswith(full,start):
   result = True
   l = len(start)
   i = 0
   while(i<l):
      if(full[i] != start[i]):
         result = False
         break
      i = i+1
   return result
 
def my_endswith(full,end):
   result = True
   l = len(end)
   i = len(full)-l
   j = 0
   while(i<len(full)):
      if(full[i] != end[j]):
         result = False
         break
      j = j+1
      i = i+1
   return result

setup()

Lab5_decimal to binary

def setup():
   print("Decimal to Binary")
   num = int(input())
   print(num,"-->",end=" ")
   p = 0
   while(num-(pow(2,p))>=0):
      p = p+1
   n = [0]*p
   i = 0
   while(i<len(n)):
      n[i] = num%2
      num = num/2
      num = round(num-0.1)
      i = i+1
   i = 0
   j = len(n)-1
   while(i<len(n)):
      print(n[j],end="")
      j = j-1
      i = i+1

setup()

Lab5_arrays

def setup():
   n = [-3,21,-5,17,21]
   display(n)
   maximum(n)
   summation(n)
   sum_positive(n)
   count_positive(n)
   average(n)
   increase(n)

def display(a):
   i = 0
   while(i<len(a)):
      print("a [",i,"] =",a[i])
      i = i+1

def maximum(a):
   i = 1
   value = a[0]
   while(i<len(a)):
      if(value<a[i]):
         value = a[i]
      i = i+1
   print("maximum value =",value)
   i = 0
   searching = True
   while(i<len(a) and searching):
      if(a[i]==value):
         searching = False
      i = i+1
   print("index of first max value =",i-1)
   i = len(a)-1
   searching = True
   while(i>=0 and searching):
      if(a[i]==value):
         searching = False
      i = i-1
   print("index of last max value  =",i+1)

def summation(a):
   i = 0
   value = 0
   while(i<len(a)):
      value = value+a[i]
      i = i+1
   print("Sum of values =",value)

def sum_positive(a):
   i = 0
   value = 0
   while(i<len(a)):
      if(a[i]>0):
         value = value+a[i]
      i = i+1
   print("Sum of positive values =",value)

def count_positive(a):
   i = 0
   count = 0
   print("positive values = ",end="")
   while(i<len(a)):
      if(a[i]>0):
         print(a[i]," ",end="")
         count = count+1
      i = i+1
   print("")
   print("count of positive values =",count)

def average(a):
   i = 0
   value = 0
   while(i<len(a)):
      value = value+a[i]
      i = i+1
   avg = value/len(a)
   print("average of values =",avg)

def increase(a):
   i = 0
   percent = int(input())
   print("new array increase by:",percent,"%")
   while(i<len(a)):
      a[i] = a[i]+(a[i]*percent/100)
      print("a [",i,"] =",a[i])
      i = i+1

setup()

กันยายน 20, 2558

Lab4x_Sum-of-1-to-N & Multiplication-Table & Sum-of-Prime-Number & Monthly-Loan-Payment

# Sum Of 1 to N
def setup():
   n = 15
   sumOfOneToN(n)
def sumOfOneToN(n):
   sum = 0
   print("N = ",n)
   while(n>0):
      sum += n
      n -= 1
   print("sum of int from 1 to N = ",sum)
setup()



# Multiplication Table
def setup():
   num = 13
   multipli_table(num)
def multipli_table(n):
   multi = 1
   print("Multiplication-Table of ",n)
   while(multi <= 12):
      print(n," x ",multi," = ",(n*multi))
      multi += 1
setup()



# Sum of Prime Number
def setup():
   final_num = 100
   primeCal(final_num)
def primeCal(n):
   result = 0
   num = 1
   print("Sum of Prime number from 1 to",n)
   while(num<=n):
      primeNum = True
      i = 2
      while(i<num and primeNum):
         if((num%i) == 0):
            primeNum = False
         i += 1
      if(primeNum):
         result += num
      num += 1
   print("result =",result)
setup()



# Monthly loan payment
def setup():
   loan = 5000
   interest_rate = 12  # percent
   loan_term = 12      # months
   loanCal(loan, interest_rate, loan_term)

def loanCal(loan, interest_rate, loan_term):
   balance = loan
   total_interest = 0
   count=1
   j = interest_rate/100/12
   payMonthly = loan*(j/(1-(pow(1+j,-loan_term))))
   print("***** Monthly Loan Payment *****")
   print(" Loan Amount : $",loan)
   print(" Loan Term   : ",loan_term," months")
   print(" Interest Rate : ",interest_rate,"%")
   print("************************************")
 
   print("Payment NO.|   Balance   |   Interest   | Principal | Unpaid Balance | Total Interest to Date")
   while (count<=loan_term):
      interest = j*balance
      principal = payMonthly-interest
      print("     ",round(count),"       ",round(balance),"         ",round(interest),"         ",round(principal), end="")
      balance -= principal
      total_interest += interest
      print("          ",round(balance),"            ",round(total_interest))
      count += 1
   print("Payment Every Month : $",payMonthly)
   print("Total of 12 Payments : $",(loan+total_interest))
   print("Total Interest : $",total_interest)
setup()

Lab4x_Grade-Calculation & Leap-Year & Power-of-Ten & Delivery-Charge

# Grade Calculation
def setup():
   score = 60
   gradeCal(score)
def gradeCal(s):
   print("Score = ",s)
   if(s>=80 and s<=100):
      print("Grade : A")
   elif(s>=70 and s<80):
      print("Grade : B")
   elif(s>=55 and s<70):
      print("Grade : C")
   elif(s>=40 and s<55):
      print("Grade : D")
   elif(s>=0 and s<40):
      print("Grade : F")
   else:
      println("Grade : -")
setup()



# Leap Year
def setup():
   year = 1800
   leapYear(year)
def leapYear(y):
   print("Year = ",y);
   if(y%400==0 or (y%4==0 and y%100!=0)):
      print("Leap Year")
   else:
      print("Not Leap Year")
setup()



# Power of ten
def setup():
   powerTen = 29
   powerOfTen(powerTen)
def powerOfTen(p):
   print("Power-of-ten = ",p)
   if(p>=100):
      if(p>100):
         print("Number = Googol++")
      else:
         print("Number = Googol")
   elif(p>=30):
      if(p>30):
         print("Number = Nonillion++")
      else:
         print("Number = Nonillion")
   elif(p>=21):
      if(p>21):
         print("Number = Sextillion++")
      else:
         print("Number = Sextillion")
   elif(p>=18):
      if(p>18):
         print("Number = Quintillion++")
      else:
         print("Number = Quintillion")
   elif(p>=15):
      if(p>15):
         print("Number = Quadrillion++")
      else:
         print("Number = Quadrillion")
   elif(p>=12):
      if(p>12):
         print("Number = Trillion++")
      else:
         print("Number = Trillion")
   elif(p>=9):
      if(p>9):
         print("Number = Billion++")
      else:
         print("Number = Billion")
   elif(p>=6):
      if(p>6):
         print("Number = Million++")
      else:
         print("Number = Million")
   else:
      print("Number = --")
setup()



# Delivery Charge
def setup():
   packaging = 2  # (1)letter
                  # (2)box
   service = 1    # (1)Next-Day-Priority
                  # (2)Next-Day-Standard
                  # (3)2-Day
   weight = 11    # oz unit for letter
                  # pound unit for box
   error = False

   if(packaging == 1):
      print("type of packaging = letter")
   elif(packaging == 2):
      print("type of packaging = box")
   else:
      print("type of packaging = Error")
      error = True

   if(service == 1):
      print("service = Next-Day-Priority")
   elif(service == 2):
      print("service = Next-Day-Standard")
   elif(service == 3):
      print("service = 2-Day")
   else:
      print("service = Error")
      error = True

   if(packaging == 1):
      print("Weight = ",weight," oz")
   elif(packaging == 2):
      print("Weight = ",weight," pound")

   #Calculation
   if(error == True):
      print("The charge = Error")
   elif(packaging == 1):
      if(service == 1):
         if(weight <= 8):
            print("The charge = $12.00")
         else:
            print("Error : Over Load")
      elif(service == 2):
         if(weight <= 8):
            print("The charge = $10.50")
         else:
            print("Error : Over Load")
      else:
         print("This service is not available")
   else:
      if(service == 1):
         value = 15.75+((weight-1)*1.25)
      elif(service == 2):
         value = 13.75+((weight-1)*1.00)
      else:
         value = 7.00+((weight-1)*0.50)
      print("The charge = $",value)

setup()

Lab4x_BMI & Circle

#Calculate body mass index (BMI)
def setup():
   weight= 60
   tall= 175
   BMI_cal(weight,tall)

def BMI_cal(weight,tall):
   BMI=weight/((tall/100)*(tall/100))
   print("Weight = " , weight)
   print("Height = " , tall)
   print("BMI = " , BMI)
setup()



#Calculate circumference and area of a circle from its diameter
def setup():
   diam=10
   circle_cal(diam)
def circle_cal(d):
   pi=22/7
   circum = 2*pi*(d/2)
   areaCir=pi*(d/2)*(d/2)
   print("Diameter = " , d)
   print("Circumference = " , circum)
   print("area of a circle = " , areaCir)
setup()

กันยายน 15, 2558

Lab4_Generic exercise

//*****sum-Of-1-to-N*****
void setup(){
  int N = 15;
  sumOfOneToN(N);
}
void sumOfOneToN(int n){
  int sum = 0;
  println("N = "+n);
  while(n>0){
    sum += n;
    n--;
  }
  println("sum of int from 1 to N = "+sum);
}

//*****Multiplication-Table*****
void setup(){
  int num = 13;
  multipli_table(num);
}
void multipli_table(int n){
  int multi = 1;
  println("Multiplication-Table of "+n);
  while(multi <= 12){
    println(n+" x "+multi+" = "+(n*multi));
    multi++;
    }
}

//*****Prime-Number*****
void setup(){
  int final_num = 100;
  primeCal(final_num);
}
void primeCal(int n){
  int num = 1;
  println("Prime number from 1 to "+n);
  while(num<=n){
    boolean primeNum = true;
    int i = 2;
    while(i<num && primeNum){
      if((num%i) == 0)
        primeNum = false;
      i++;
    }
    if(primeNum)
      print(num+" ");
    num++;
  }
}
//*****Monthly-loan-payment*****
void setup() {
  float loan = 5000;
  float interest_rate = 12; //percent
  int loan_term = 12; //months
  loanCal(loan, interest_rate, loan_term);
}

void loanCal(float loan, float interest_rate, float loan_term) {
  float payMonthly, balance = loan, total_interest=0;
  float interest, principal, j;
  int count=1;
  j = interest_rate/100/12;
  payMonthly = loan*(j/(1-(pow(1+j,-loan_term))));
  println("***** Monthly Loan Payment *****");
  println(" Loan Amount : $"+loan);
  println(" Loan Term   : "+loan_term+" months");
  println(" Interest Rate : "+interest_rate+"%");
  println("************************************");
  
  println("Payment NO.|   Balance   |   Interest   | Principal | Unpaid Balance | Total Interest to Date");
  while (count<=loan_term) {
    interest = j*balance;
    principal = payMonthly-interest;
    print("     "+count+"       "+balance+"      "+interest+"         "+principal);
    balance -= principal;
    total_interest += interest;
    println("       "+balance+"          "+total_interest);
    count++;
  }
  println("Payment Every Month : $"+payMonthly);
  println("Total of 12 Payments : $"+(loan+total_interest));
  println("Total Interest : $"+total_interest);
}

Lab4_songs

int limit=0;
int light_brown=#F7DEA7;
int white=255;
color screen;
color Line=255;
boolean dropNote=false;
int noteY=0;
void draw() {
  int noteX=10;
  size(350, 185);
  background(screen);
  limit++;
  limit %= 180;
  draw_song();
  if (dropNote) {
    while (noteX<width) {
      note(noteX);
      noteX += 25;
    }
      if (noteY>200) {
        dropNote=false;
        noteY=0;
   
    }
  }
}
void draw_song() {
  int posX=100;
  posX+=limit;
  noStroke();
  //draw"THE"
  fill(Line);
  rect(posX-25, 10, 70, 30); //blank"THE"
  fill(screen);
  rect(posX-25, 15, 7, 25);
  rect(posX-13, 15, 7, 25); //T
  rect(posX, 10, 15, 12);
  rect(posX, 27, 15, 13); //H
  rect(posX+20, 10, 3, 30);
  rect(posX+28, 15, 17, 7);
  rect(posX+28, 27, 17, 8); //E
  triangle(posX+33, 10, posX+45, 45, posX+45, 10);
  //draw"SCRIPT"
  fill(Line);
  arc(45, 75, 60, 60, HALF_PI, TWO_PI);
  arc(45, 131, 70, 70, HALF_PI+PI, TWO_PI+HALF_PI); //S
  arc(130, 105, 110, 110, QUARTER_PI+PI/32, TWO_PI-QUARTER_PI-PI/32); //C
  rect(165, 50, 20, 10);
  rect(165, 105, 20, 10);
  arc(185, 82.5, 60, 65, 3*PI/2, 5*PI/2);
  quad(170, 115, 185, 115, 215, 147, 215, 163); //R
  rect(220, 50, 10, 120); //I
  rect(235, 50, 10, 120);
  rect(245, 50, 20, 10);
  rect(245, 105, 20, 10);
  arc(265, 82.5, 60, 65, 3*PI/2, 5*PI/2); //P
  quad(265, 50, 330, 50, 335, 60, 265, 60);
  rect(300, 50, 10, 120); //T
  fill(screen);
  arc(45, 76, 40, 40, HALF_PI, TWO_PI);
  arc(45, 131, 50, 50, HALF_PI+PI, TWO_PI+HALF_PI); //S
  arc(130, 105, 90, 90, QUARTER_PI, TWO_PI-QUARTER_PI); //C
  triangle(147, 50, 155, 80, 155, 50);
  arc(185, 82.5, 40, 45, 3*PI/2, 5*PI/2); //R
  quad(220, 65, 230, 60, 230, 65, 220, 70); //I
  arc(265, 82.5, 40, 45, 3*PI/2, 5*PI/2); //P
  triangle(220, 170, 310, 130, 310, 170);
  fill(Line);
  rect(155, 50, 10, 97); //R
}
void note(int noteX) {
  fill(Line);
  ellipse(noteX, noteY, 15, 15);
  stroke(Line);
  strokeWeight(3);
  line(noteX+6, noteY, noteX+6, noteY-35);
  line(noteX+6, noteY-30, noteX+13, noteY-10);
  line(noteX+13, noteY-10, noteX+12, noteY-5);
  noteY++;
}
void mouseClicked() {
  if (mouseButton==RIGHT) {
    white *= -1;
    Line += white;
    screen += light_brown;
    light_brown*=-1;
  } else if (mouseButton==LEFT) {
    dropNote=true;
  }
}
 

Lab4_books

int wink;
float spin;
void draw() {
  size(300, 400);
  background(0);  //colorBlack
  draw_book();
  if (keyPressed) {
    if (key==CODED) {
      if (keyCode==LEFT) spin+=PI/32;
      else if (keyCode==RIGHT) spin-=PI/32;
    }
  }
  fill(255);
  text("Pressed LEFT or RIGHT arrow.", 75, 350);
  fill(0);
}
void draw_book() {
  int posX=155, posY=150;
  float addPos=0,count=0;
  if (frameCount%50<=25) wink=1;
  else wink=0;
  //bones
  while (count<2) {
    translate(155, 150);
    rotate(spin+addPos);
    fill(255);  //colorWhite
    noStroke();
    beginShape();
    vertex(-90, -110);
    vertex(110, 90);
    vertex(110, 110);
    vertex(90, 110);
    vertex(-110, -90);
    vertex(-110, -110);
    endShape();
    beginShape();
    vertex(90, -110);
    vertex(-110, 90);
    vertex(-110, 110);
    vertex(-90, 110);
    vertex(110, -90);
    vertex(110, -110);
    endShape();
    ellipse(-100, -120, 30, 30);
    ellipse(-120, -100, 30, 30);
    ellipse(100, -120, 30, 30);
    ellipse(120, -100, 30, 30);
    ellipse(120, 100, 30, 30);
    ellipse(100, 120, 30, 30);
    ellipse(-100, 120, 30, 30);
    ellipse(-120, 100, 30, 30);
    rotate(-spin-addPos);
    translate(-155, -150);
    addPos=PI/4;
    count++;
  }
  //skull & hat
  stroke(0);
  strokeWeight(4);
  ellipse(posX, posY+90, 80, 90);
  fill(145, 55, 25);  //colorBrown
  arc(posX, posY, 170, 170, PI+PI/16, TWO_PI-PI/16);
  fill(255, 210, 50); //colorYellow
  arc(posX, posY, 170, 170, PI+PI/7, TWO_PI-PI/7);
  arc(posX, posY+30, 320, 115, PI+PI/5, TWO_PI-PI/5);
  fill(255); //colorWhite
  arc(posX, posY, 170, 170, 0, PI);
  arc(posX, posY, 170, 30, PI, TWO_PI);
  //detail
  fill(0);
  ellipse(posX, posY+60, 20, 20); //nose
  ellipse(posX+35, posY+25, 50, 50*wink); //R-eye
  ellipse(posX-35, posY+25, 50, 50*wink); //L-eye
  noFill();
  arc(posX, posY, 195, 195, HALF_PI-PI/8, HALF_PI+PI/8);
  arc(posX, posY, 220, 220, HALF_PI-PI/8+PI/48, HALF_PI+PI/8-PI/48);
  line(posX-20, posY+85, posX-23, posY+105);
  line(posX, posY+85, posX, posY+110);
  line(posX+20, posY+85, posX+23, posY+105);
  //book
  strokeWeight(3);
  stroke(100); //lncolorGray
  arc(5, 400, 16, 50, HALF_PI, 3*PI/2);
  line(8, 0, 8, 375);
  line(8, 375, 300, 375);
  line(7, 380, 300, 380);
  line(6, 385, 300, 385);
  line(5, 390, 300, 390);
  line(4, 395, 300, 395);
  wink++;
}
 

Lab4_movies

int posX=100,posY=100;
int speed=1,assist=1;
boolean hold=false;
void draw(){
  size(300,250);
  background(#FF7700); //red
  draw_movie();
  if(hold) saber();
}
void draw_movie(){
  strokeWeight(3);
  stroke(100); //lnColorGray
  fill(0); //colorBlack
  quad(posX-95,posY+115,posX+145,posY+115,posX+109,posY+19,posX-59,posY+19); //wing
  arc(posX+25,posY-90,550,455,HALF_PI-PI/7,HALF_PI+PI/7); //wing
  quad(posX-53,posY+15,posX+103,posY+15,posX+75,posY+125,posX-25,posY+125); //face
  arc(posX+25,posY-10,160,160,PI-PI/8,TWO_PI+PI/8); //head
  quad(posX+37,posY+21,posX+90,posY+21,posX+145,posY+115,posX+112,posY+15);
  quad(posX+13,posY+21,posX-40,posY+21,posX-95,posY+115,posX-63,posY+15);
  arc(posX+75,posY+20,75,60,PI,TWO_PI); //R-eyebrow
  arc(posX-25,posY+20,75,60,PI,TWO_PI);  //L-eyebrow
  fill(255); //colorWhite
  ellipse(posX+55,posY+45,70,35); //R-eye
  ellipse(posX-5,posY+45,70,35); //L-eye
  fill(0);
  triangle(posX-25,posY+125,posX+75,posY+125,posX+25,posY+65); //mouth
  stroke(255); //lnColorWhite
  line(posX-9,posY+108,posX-9,posY+125);
  line(posX+8,posY+88,posX+8,posY+125);
  line(posX+25,posY+80,posX+25,posY+125);
  line(posX+42,posY+88,posX+42,posY+125);
  line(posX+59,posY+108,posX+59,posY+125);
  stroke(100);
  fill(255);
  rect(posX+13,posY+65,25,15); //nose
  fill(0);
  rect(posX+15,posY-92,20,145);
  quad(posX+15,posY+53,posX+35,posY+53,posX+38,posY+65,posX+13,posY+65);
  arc(posX+25,posY+125,100,40,0,PI); //chin
  fill(255);
  ellipse(posX+70,posY+125,10,10);
  ellipse(posX-20,posY+125,10,10);
  posX+=speed;
  posX %= 250;
}
void saber(){
  int count=0,addX=0;
  while(count<2){
  strokeWeight(14);
  stroke(#FF0000);
  line(posX-95+addX,225,posX-95+addX,20);
  strokeWeight(8);
  stroke(255);
  line(posX-95+addX,220,posX-95+addX,23);
  strokeWeight(3);
  stroke(100);
  fill(200);
  rect(posX-100+addX,225,10,25);
  addX=235;
  count++;
  }
}
void mouseClicked(){
  if(mouseButton==RIGHT){
    assist*=(-1);
    speed+=assist;
  }
  if(mouseButton==LEFT){
    if(hold==true) hold=false;
    else hold=true;
  }
}
 

กันยายน 13, 2558

Lab4_birds

float cloudX=0;
float move=1;
void draw(){
  int count= -2;
  int posX, posY;
  size(500,500);
  background(#00AAFF);
  cloud();
  while(count<3){
    posX=mouseX+(count*60);
    posY=mouseY+(count*60);
    translate(posX,posY);
    strokeWeight(1.5);
    bird();
    translate(-posX,-posY);
    count++;
  }
}
void bird(){
  rotate(PI/5);
  fill(#FF0000);
  ellipse(0,-25,10,20);  //hair
  ellipse(-10,-25,10,20);
  rotate(-PI/5);
  wing();
  ellipse(0,0,50,50);    //body
  fill(#FFFF00);
  arc(0,0,50,50,PI/4,3*PI/4);
  fill(255);
  ellipse(-10,-5,15,10); //left eye
  fill(0);
  ellipse(-10,-5,5,5);
  fill(255);
  ellipse(10,-5,15,10);  //right eye
  fill(0);
  ellipse(10,-5,5,5);
  triangle(0,0,-10,10,10,10); //beak
}
void wing(){
  float roll;
  if((frameCount%50)<=25)
    roll=PI/16;
  else
    roll=-PI/16;
  rotate(roll);
  ellipse(-30,0,50,20);  //left wing
  rotate(-2*roll);
  ellipse(30,0,50,20);   //right wing
  rotate(roll);
}
void cloud(){
  noStroke();
  fill(255);
  ellipse(510-cloudX,100,100,30);
  ellipse(30+cloudX,175,120,60);
  ellipse(450-cloudX,300,75,50);
  ellipse(100+cloudX,275,85,45);
  ellipse(350-cloudX,405,215,140);
  stroke(0);
  cloudX+=move;
  if (cloudX>=450)
    move*=-1;
  else if (cloudX<=-50)
    move*=-1;
}
 

Lab4_balloons

void draw(){
  int count=-1;
  size(200,400);
  background(255);
  while(count<2){
    int posX=width/2;
    posX+=(55*count);
    draw_balloon(posX);
    count++;
  }
}
void draw_balloon(int x){
  int posY=mouseY;
  color ball;
  if(mouseY<=50){
    posY=50;
    ball=#00FF00;
  }
  else if(mouseY>=300){
    posY=300;
    ball=#FF0000;
  }
  else ball=255;
  strokeWeight(1.5);
  fill(ball);
  line(x,posY,x,posY+100);
  ellipse(x,posY,50,50);
}
 

กันยายน 06, 2558

Lab3_Generic exercise

//*****Grade Calculation*****
void setup(){
  int score = 60;
  gradeCal(score);
}
void gradeCal(int s){
  println("Score = "+s);
  print("Grade : ");
  if(s>=80 && s<=100) println("A");
  else if(s>=70 && s<80) println("B");
  else if(s>=55 && s<70) println("C");
  else if(s>=40 && s<55) println("D");
  else if(s>=0 && s<40) println("F");
  else println("-");  //for error
}


//*****Leap Year*****
void setup(){
  int year = 1800;
  leapYear(year);
}
void leapYear(int y){
  println("Year = "+y);
  if( y%400==0 || (y%4==0 && !(y%100==0)) )
  println("Leap Year");
  else println("Not Leap Year");
}
//*****power-of-ten*****
void setup(){
  int powerTen = 18;
  powerOfTen(powerTen);
}
void powerOfTen(int p){
  println("Power-of-ten = "+p);
  print("Number = ");
  if(p>=100){
    print("Googol");
    if(p>100) println("++");
  }
  else if(p>=30){
    print("Nonillion");
    if(p>30) println("++");
  }
  else if(p>=21){
    print("Sextillion");
    if(p>21) println("++");
  }
  else if(p>=18){
    print("Quintillion");
    if(p>18) println("++");
  }
  else if(p>=15){
    print("Quadrillion");
    if(p>15) println("++");
  }
  else if(p>=12){
    print("Trillion");
    if(p>12) println("++");
  }
  else if(p>=9){
    print("Billion");
    if(p>9) println("++");
  }
  else if(p>=6){
    print("Million");
    if(p>6) println("++");
  }
  else{
    print("--");
  }
}

//*****Delivery-Charge*****
void setup(){
  int packaging = 2;   // (1)letter
                                  // (2)box
  int service = 1;                // (1)Next-Day-Priority
                                          // (2)Next-Day-Standard
                                          // (3)2-Day
  float weight = 11;   // oz unit for letter
                                  // pound unit for box
  float value;
  boolean error = false;

  print("type of packaging = ");
  if(packaging == 1) println("letter");
  else if(packaging == 2) println("box");
  else {
    println("Error");
    error = true;
  }
  print("service = ");
  if(service == 1) println("Next-Day-Priority");
  else if(service == 2) println("Next-Day-Standard");
  else if(service == 3) println("2-Day");
  else {
    println("Error");
    error = true;
  }
  print("Weight = "+weight+" ");
  if(packaging == 1) println("oz");
  else if(packaging == 2) println("pound");

  //Calculation
  print("The charge = ");
  if(error == true) println("Error");
  else if(packaging == 1){
    if(service == 1){
      if(weight <= 8) println("$12.00");
      else println("Error : Over Load");
    }
    else if(service == 2){
      if(weight <= 8) println("$10.50");
      else println("Error : Over Load");
    }
    else println("not available");
  }
  else if(packaging == 2){
    if(service == 1){
      value = 15.75+((weight-1)*1.25);
    }
    else if(service == 2){
      value = 13.75+((weight-1)*1.00);
    }
    else value = 7.00+((weight-1)*0.50);
    println("$"+value);
  }
}