📜  TCS Codevita |孔和球

📅  最后修改于: 2021-09-24 04:59:12             🧑  作者: Mango

给定两个分别由NM 个整数组成的 H[]B[]数组,分别表示孔和球的直径。使M个球在有N个孔的斜面上从A滚动到B ,每个球具有不同的深度,如下图所示:

任务是按照球释放的顺序找到每个球的最终位置,考虑以下因素:

  • 如果球的直径小于或等于孔的直径,则球将落入孔中。
  • 如果 i个球落入一个洞H i 中,它就会被填满。
  • 如果一个洞是满的,那么就不会再有球掉进去了。
  • 一个球将从A到达 B ,当且仅当它没有落入任何一个孔中。
  • 如果一个球在洞P i 中,那么它的位置是i 。如果球到达底部点 B,则将其位置设为0

例子:

处理方法:按照以下步骤解决问题:

  • 初始化的大小为N的阵列位置[]存储每个球的最终位置和大小为N的一个阵列深度[]存储每个孔的容量。
  • 使用变量i迭代范围[1, N]并将孔 [i]的初始深度 [i]设置为i+1
  • 使用变量i遍历数组ball[]并执行以下操作:
    • 使用变量j以相反的顺序迭代数组hole[]。
      • 检查孔的直径是否大于或等于球的直径,即, hole[j] ≥ ball[i] ,如果该孔未满,即深度[j] > 0,则放置通过在position[]数组中附加 j + 1并将孔的深度减少1并跳出循环,从而将球放入该孔中。
    • 如果球不适合任何孔(已到达斜坡的末端),则在position[]数组中附加 0。
  • 完成上述步骤后,打印存储在数组position[] 中的值作为结果。

下面是上述方法的实现:

Python3
# Python program for the above approach
  
# Function to find and print the final
# position of balls
def ballPositionFinder(diameter_of_holes,
                       diameter_of_balls):
    
    max_hole_limit_counter = []
    position_value = []
      
    # Stores the positions of balls
    ball_positions = []
  
    # Determine the maximum balls a hole
    # can store and note the position
    # of holes in position_value
    for i in range(1, len(diameter_of_holes)+1):
        max_hole_limit_counter.append(i)
        position_value.append(i)
  
    # Iterate over all possible holes
    # for every ball released
    for i in range(0, len(diameter_of_balls)):
        for j in range(1, len(diameter_of_holes)+1):
  
            # Place ball in hole if it fits
            # in and if hole is not full
            if (diameter_of_holes[-j] >= diameter_of_balls[i]) and (
                    max_hole_limit_counter[-j] != 0):
                
                ball_positions.append(position_value[-j])
                max_hole_limit_counter[-j] -= 1
                break
  
            # If ball has reached at end B
            if j == len(diameter_of_holes):
                ball_positions.append(0)
                break
  
    return ball_positions
  
  
# Driver Code
if __name__ == "__main__":
    
    diameter_of_holes = [21, 3, 6]
      
    diameter_of_balls = [20, 15, 5, 7, 10, 4,
                         2, 1, 3, 6, 8]
  
    # Function Call
    output = ballPositionFinder(diameter_of_holes,
                                diameter_of_balls)
    print(*output, sep =' ')


输出:
1 0 3 0 0 3 3 2 2 0 0

时间复杂度: O(N*M)
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。