Skip to content

Instantly share code, notes, and snippets.

@mkeyno
Last active May 11, 2021 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkeyno/9b56b2e0ab2b974ba9e5ad02e4208e64 to your computer and use it in GitHub Desktop.
Save mkeyno/9b56b2e0ab2b974ba9e5ad02e4208e64 to your computer and use it in GitHub Desktop.

Dispensing package algorithm

Regards to the task description, there is a packaging machine that dispenses the product base of packet size and weight capacity. Number of the packed items should not exceed the packed size or weight capacity.

The algorithm is to first read this packed capacity information then dispense of product bath inside the packed in each iteration, the maximum item that can put in the packed will be defined by comparing the available index, available weight, and available items.
If remain item greater than the available space in the packet, then a new packed defined. For simplicity python script has been chosen for this algorithm. before printing each packet sorted base on item's length

following is the sample code for this task.
To feed data to the program use

cat input.txt | sort.py

or

python < input.txt sort.py

code

def check_number(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            raise ValueError('argument is not a string of number')

class Pack():
    def __init__(self):
        self.available_item=0
        self.available_weight=0
        self.total_weight=0
        self.total_item=0
        self.biggest_lenght=0
        self.pack=[]
           
    def show_sorted(self):
        if   Sort_order=="SHORT_TO_LONG":
               self.pack=sorted(self.pack, key=lambda x: x[2])#operator.itemgetter(2)
        elif Sort_order=="LONG_TO_SHORT":
               self.pack=sorted(self.pack, key=lambda x: x[2],reverse=True)#operator.itemgetter(2)

# initialized the first packet        
Sort_order="NATURAL"
max_pieces_per_pack=1
max_weight_per_pack=1 
p=Pack() 
# create list of packets 
list_of_packs=[p]
current_pack_num=0
current_pack=list_of_packs[current_pack_num]

def processString(input):
    global Sort_order,max_pieces_per_pack,max_weight_per_pack,current_pack_num,current_pack
    
    List=input.split(',')
    
    if   len(List)==3: # process packet information
        
        Sort_order=List[0]
        max_pieces_per_pack=check_number(List[1])
        max_weight_per_pack=check_number(List[2])

        current_pack.available_item  =max_pieces_per_pack
        current_pack.available_weight=max_weight_per_pack
        
    elif len(List)==4:# process batch item information
            
            item_id      =check_number(List[0])
            item_length  =check_number(List[1])
            item_quantity=check_number(List[2])
            piece_weight =check_number(List[3]) 


            while True:  # start dispencing
            
                avilabale_weight=int(current_pack.available_weight/piece_weight)
                # check maximum item that can put in packet
                can_put         =min(avilabale_weight,current_pack.available_item,item_quantity)
             
                if  can_put==item_quantity:  #we have more space in packet so let process anothor line batch item
                    
                    current_pack.total_weight     += can_put*piece_weight
                    current_pack.available_item   -= item_quantity 
                    current_pack.available_weight -= can_put*piece_weight
                    # add to list
                    current_pack.pack.append([item_id,item_length,item_quantity,piece_weight])
                    # record maximum lenght
                    if item_length>= current_pack.biggest_lenght:
                        current_pack.biggest_lenght=item_length
                         #update contationer
                    
                    break
                
                 
                
                elif can_put==0: # there is no more space in packet , let use new packet 

                    p=Pack() 
                    list_of_packs.append(p)
                    current_pack_num+=1
                    current_pack=list_of_packs[current_pack_num]
                    
                    current_pack.available_item  = max_pieces_per_pack
                    current_pack.available_weight= max_weight_per_pack
                    current_pack.total_weight    = 0
    
                else: #dispencing
                    current_pack.total_weight     += can_put*piece_weight
                    current_pack.available_weight -= can_put*piece_weight
                    
                    current_pack.pack.append([item_id,item_length,can_put,piece_weight])
                    
                    current_pack.available_item -=  can_put
                    item_quantity               -=  can_put
                    
                    # record maximum lenght
                    if item_length>= current_pack.biggest_lenght:
                        current_pack.biggest_lenght=item_length
                            
    else : 
          print('input value error')      
   


while True:
    try:
        x = input()
        if x == "" :
            for i in range(len(list_of_packs)):
             print("Pack Number ",i+1)
             list_of_packs[i].show_sorted() # first sort the items in packet
             for l in list_of_packs[i].pack:
                    print(l)
             print( f'Pack Length: { list_of_packs[i].biggest_lenght}, Pack Weight: {list_of_packs[i].total_weight:.2f}')
            break
        else:
            #lines.append(x );
            processString(x)
    except EOFError as e:
        print(e)  
    
print("--end---")    
    
    
    
    
    
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment