Re: [問題] 循環數列

作者: celestialgod (天)   2016-04-26 21:31:03
※ 引述《PILIPALAPON (pilipalapon)》之銘言:
: [問題類型]:
: 程式資訊
: [軟體熟悉度]:
: 入門
: [問題敘述]:
: a為7個1到7隨機取後不放回的數
: a=sample(1:7,7,replace=T)
: 當a為1時 b=2 c=3 d=4 e=5 f=6 g=7
: 當a為2時 b=3 c=4 d=5 e=6 f=7 g=1
: 當a為3時 b=4 c=5 d=6 e=7 f=1 g=2
: 以此類推...
: [程式範例]:
: 目前只想到用迴圈直接寫,想請版友提供更快更好的方法
: [環境敘述]:
: R3.2.4
a <- sample.int(7L, 7L) # [1] 6 7 2 5 1 3 4
out <- sweep(replicate(7L, 1L:7L), 2, a, '+')
out[out > 7] <- out[out > 7] - 7
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 7 1 3 6 2 4 5
# [2,] 1 2 4 7 3 5 6
# [3,] 2 3 5 1 4 6 7
# [4,] 3 4 6 2 5 7 1
# [5,] 4 5 7 3 6 1 2
# [6,] 5 6 1 4 7 2 3
# [7,] 6 7 2 5 1 3 4
# 一次pipe得到答案 (這個絕對是太無聊):
library(pipeR)
library(plyr)
sample.int(7L, 7L) %>>% (sweep(replicate(7L, 1L:7L), 2, ., '+')) %>>%
mapvalues(8:14, 1:7)

Links booklink

Contact Us: admin [ a t ] ucptt.com