当每一列和每一行的总和已知时,如何找到仅由0和1组成的精确矩阵

时间:2018-09-13 03:59:15

标签: r matrix

当要知道每一列和每一行的总和时,我想找到仅由0和1组成的精确矩阵。例如,如图片所示,知道每一行的总和,如何找到满足的精确矩阵。矩阵的元素只能是0或1。 这是列和行的总和,列和行的长度不相等。

col_sum <- c(3,3,4,4,5,5,4)
row_sum <- c(6,5,4,4,3,3,3,0)

an example

1 个答案:

答案 0 :(得分:1)

解决方案不一定是唯一的;但是,我们可以使用线性编程找到可能的多个解决方案之一。首先设置一个测试用例。

col_sum <- c(3,3,4,4,5,5,4)
row_sum <- c(6,5,4,4,3,3,3,0)

# solve using linear programming
m <- length(row_sum)
n <- length(col_sum)
obj <- numeric(m*n)
const.mat <- rbind(t(rep(1, n) %x% diag(m)), t(diag(n) %x% rep(1, m)))
const.rhs <- c(row_sum, col_sum)
res <- lp("min", obj, const.mat, "=", const.rhs, all.bin = TRUE)
soln <- matrix(res$solution, m)

# check that row and column totals of soln are correct
all.equal(c(rowSums(soln), colSums(soln)), c(row_sum, col_sum))
## [1] TRUE

问题示例

func sendNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Timer"
    content.body = "30 Seconds"
    content.sound = UNNotificationSound.default()

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.001, repeats: false)
    let request = UNNotificationRequest(identifier: "timer.request", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request) { (error) in
        if let error = error{
            print("Error posting notification:\(error.localizedDescription)")
        } else{
            print("notification scheduled")
        }
    }
}


@objc func setUpReminder()
{
    UNUserNotificationCenter.current().requestAuthorization(
        options: [.alert,.sound])
    {(granted, error) in

       self.sendNotification()
   }
}