修复随机列表中的第一个和最后一个数字

Fixing the First and Last Numbers in a Random List

我使用此代码生成这些随机数(对应于图形的边列表)使得 ():

见下文:

d = 15

relations = data.frame(tibble(
  from = sample(data$d),
  to = lead(from, default=from[1]),
))

> relations
   from to
1     1 11
2    11  7
3     7  5
4     5 10
5    10 13
6    13  9
7     9 15
8    15  2
9     2  3
10    3  4
11    4  8
12    8  6
13    6 12
14   12 14
15   14  1

如果我重新运行上面的代码,它会(自然地)产生一个不同的列表:

relations
   from to
1     6  9
2     9  2
3     2  5
4     5  8
5     8 13
6    13  1
7     1 14
8    14  3
9     3 11
10   11 12
11   12  7
12    7 15
13   15  4
14    4 10
15   10  6

例如,我可以让第一个数字和最后一个数字始终为“7”吗?

#example 1
   from to
1     7 11
2    11  1
3     1  5
4     5 10
5    10 13
6    13  9
7     9 15
8    15  2
9     2  3
10    3  4
11    4  8
12    8  6
13    6 12
14   12 14
15   14  7

#example 2
   from to
1     7  9
2     9  2
3     2  5
4     5  8
5     8 13
6    13  1
7     1 14
8    14  3
9     3 11
10   11 12
11   12  6
12    6 15
13   15  4
14    4 10
15   10  7

在上面的示例(示例 1、示例 2)中,我将我制作的前两个随机列表手动替换为 7 的第一个数字和最后一个数字 - 然后也替换了替换数字。

例如,我想我想出了如何做到这一点:

#run twice to make sure the output is correct

  relations = data.frame(tibble(
      from = sample(data$d),
      to = lead(from, default=from[1]),
    ))
    
    orig_first = relations[1,1]
    
    
    relations[1,1] = 7
    relations[15,2] = 7
    
    relation = relations[-c(1,15),]
    r1 = relations[1,]
    r2 = relations[15,]
    
    final_relation = rbind(r1, relation, r2)

#output 1 : seems correct (starts with 7, ends with 7, all nodes visited exactly once)

   from to
1     7  8
2     8  4
3     4  7
4     7 13
5    13  1
6     1 14
7    14  6
8     6  9
9     9 11
10   11 10
11   10 12
12   12  2
13    2  5
14    5 15
15   15  7

#output 2: looks correct

   from to
1     7  9
2     9  2
3     2  1
4     1  6
5     6  3
6     3 10
7    10 11
8    11 14
9    14 12
10   12  7
11    7 13
12   13  4
13    4 15
14   15  8
15    8  7

谢谢!

这里有一个方法可以做到这一点 -

library(dplyr)

set.seed(2021)
d = 15
fix_num <- 7

relations = tibble(
  from = c(fix_num, sample(setdiff(1:d, fix_num))),
  to = lead(from, default=from[1]),
)

relations

# A tibble: 15 x 2
#    from    to
#   <dbl> <dbl>
# 1     7     8
# 2     8     6
# 3     6    11
# 4    11    15
# 5    15     4
# 6     4    14
# 7    14     9
# 8     9    10
# 9    10     3
#10     3     5
#11     5    12
#12    12    13
#13    13     1
#14     1     2
#15     2     7