# 2020 基礎実習 R programming１

```# creating example vectors
students = paste("s", 1:20, sep = "")
suite = rep(c("s","h","c","d"),13)
ns = sort(rep(1:13,4))
cards  = paste(suite, ns, sep="")

# samples
rand_select = sample(1:10, 2)
rand_perm = sample(1:10)
with_replacemnt = sample(0:1, 10, replace = T)
temp = sample(1:5, 5, replace = T)

# concrete example

# random selection
pointed <- sample(students,2)

# random permutation
randID= sample(1:20)
h1 = students[randID[1:10]]
h2 = students[randID[11:20]]

h1order = sample(h1)
h2order = sample(h2)

shuffled = sample(cards)
cardPlay = data.frame(p1 = shuffled[1:5], p2 = shuffled[6:10], p3 = shuffled[11:15])

# with replacement

# for loop
num = 1:5
chr = c("a","b","c","d","e")
for (i in num){
print(i)
}
for (i in chr){
print(i)
}
for (i in num){
print(chr[i])
}

p1 = p2 = p3 = rep("joker",5)
Ncard = 5
Nplayer = 3
cardSeq = seq(1, Ncard*Nplayer, Nplayer)
cardN = 0
for (i_card in cardSeq){
cardN = cardN + 1
p1[cardN] = shuffled[i_card]
p2[cardN] = shuffled[i_card+1]
p3[cardN] = shuffled[i_card+2]
}

p1 = shuffled[seq(1,15,3)]
p2 = shuffled[seq(2,15,3)]
p3 = shuffled[seq(3,15,3)]

players = matrix("joker",nrow = Ncard, ncol = Nplayer)
colnames(players) <- c("p1","p2","p3")
cardN = 0
for (i_card in 1:Ncard){
for (i_player in 1:Nplayer){
cardN = cardN + 1
players[i_card, i_player] = shuffled[cardN]
}
}

players\$p1 = shuffled[seq(1,15,3)]
players\$p2 = shuffled[seq(2,15,3)]
players\$p3 = shuffled[seq(3,15,3)]

p1WinC = p2WinC = tie = 0
Nplay = 10
for (i_play in 1:Nplay){
p1 = sample(1:6,1)
p2 = sample(1:6,1)
if (p1 > p2){
p1WinC = p1WinC + 1
} else {
if (p2 > p1){
p2WinC = p2WinC + 1
} else {
tie = tie + 1
}
}
}

result = sample(c(0,1,2),10, replace=T, prob = c(2/12,5/12,5/12))

win_thres = 5
p1WinC = p2WinC = tie = 0

while(max(c(p1WinC, p2WinC)) < win_thres){
p1 = sample(1:6,1)
p2 = sample(1:6,1)
if (p1 > p2){
p1WinC = p1WinC + 1
} else {
if (p2 > p1){
p2WinC = p2WinC + 1
}
}
}
if (p1WinC>p2WinC){
print("player 1 won")
} else {
print("player 2 won")
}

win_thres = 5
p1WinC = p2WinC = tie = 0

repeat{
p1 = sample(1:6,1)
p2 = sample(1:6,1)
if (p1 > p2){
p1WinC = p1WinC + 1
} else {
if (p2 > p1){
p2WinC = p2WinC + 1
}
}
if(max(c(p1WinC, p2WinC)) >= win_thres){
if (p1WinC>p2WinC){
print("player 1 won")
} else {
print("player 2 won")
}
break
}
}

vec = sample(1:15)
len_vec = length(vec)
#vec = 1:15
for (loop1 in 1:(len_vec-1)){
for (loop2 in 2:(len_vec - loop1 + 1)){
if (vec[loop2] < vec[(loop2 - 1)]){
temp_num = vec[loop2]
vec[loop2] = vec[(loop2-1)]
vec[(loop2-1)] = temp_num
}
}
print(paste("result after loop1 = ", loop1))
print(vec)
}

vec = sample(1:15)
len_vec = length(vec)
#vec = 1:15
for (loop1 in 1:(len_vec-1)){
if (all(1:15 == vec)) {
print("sorted")
print(vec)
break
}
for (loop2 in 2:(len_vec - loop1 + 1)){
if (vec[loop2] < vec[(loop2 - 1)]){
temp_num = vec[loop2]
vec[loop2] = vec[(loop2-1)]
vec[(loop2-1)] = temp_num
}
}
print(paste("result after loop1 = ", loop1))
print(vec)
}
```