사다리 게임
input:
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
output:
a - 5
b - 2
c - 3
d - 6
e - 1
f - 4
29개의 풀이가 있습니다.
오랜만이네요.
파이썬 3.6입니다.
inp = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
'''
a, *b, c = inp.splitlines()
c = list(c)
for line in b:
for i, x in enumerate(line):
if i % 2 == 1 and x == '-':
c[i-1], c[i+1] = c[i+1], c[i-1]
result = list(zip(a, c))[::2]
for x, y in result:
print(f'{x} - {y}')
inp = '''\
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
board = [i for i in inp.split('\n')]
def ladder(v):
def check(x,y):
if y+1<len(board[0]) and board[x][y+1] == '-': return 2
elif 0<=y-1 and board[x][y-1] == '-': return -2
else: return 0
x,y = 0,board[0].find(v)
while x < len(board)-1:
x += 1
y += check(x,y)
return board[x][y]
for i in board[0].split(): print(i,ladder(i),sep=' - ')
input = '''
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
'''
ladder = [[j for j in i] for i in input.strip().split('\n')]
rows = len(ladder)
cols = len(ladder[0])
for i in range(0, cols, 2):
# 위치
p = i
for j in range(1, rows):
# 오른쪽에 - 가 있으면
if p + 1 < cols and ladder[j][p + 1] == '-':
p += 2
elif p - 1 >= 0 and ladder[j][p - 1] == '-':
p -= 2
print(ladder[0][i], '-', ladder[rows - 1][p])
class Main {
static char[][] map;
static int n,m;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = Integer.parseInt(sc.nextLine()); // 사다리 길이
m = Integer.parseInt(sc.nextLine())*2 - 1; //
map = new char[n][m];
for (int i=0; i<n; i++) {
String s = sc.nextLine();
for (int j=0; j<m; j++) {
map[i][j] = s.charAt(j);
}
} // 사다리판 입력
for (int i=0; i<m; i += 2) {
int a = i;
for (int j=0; j<n; j++) {
if (a-1 >=0 && map[j][a-1] == '-') { // 왼쪽으로 건너갈 때
a -= 2;
} else if (a+1 < m && map[j][a+1] == '-') { // 오른쪽으로 건나갈 때
a += 2;
}
}
System.out.println(map[0][i] + " - " + map[n-1][a]);
}
}
}
Ruby
def ladder(game_str)
swap = ->a,r { (1..r.size).each {|i| a[i-1,3] = a[i-1,3].reverse if r[i] == "-"}; a}
lanes, *rows, nums = game_str.split("\n")
lanes, result = lanes.split, rows.reduce(lanes, &swap).split.zip(nums.split).to_h
puts lanes.map {|c| "#{c} - #{result[c]}"}
end
Test
game = <<-eos
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
eos
result = <<-eos
a - 5
b - 2
c - 3
d - 6
e - 1
f - 4
eos
expect { ladder(game) }.to output(result).to_stdout
좋은 문제 같습니다~
input1 = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
data = input1.split("\n")
data1 = data[0].split()
data2 = data[-1].split()
for line in data[1:-1]:
for i, sw in enumerate(line.split('|')):
if sw == '-':
data2[i-1], data2[i] = data2[i], data2[i-1]
for d1, d2 in zip(data1, data2):
print(d1, "-", d2)
data = \
'''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
data = data.split('\n')
player_idx = {x[1]:x[0] for x in enumerate(data.pop(0)) if x[1] != ' '}
for line in data[:-1]:
for p, i in player_idx.items():
if i >= 2 and line[i - 1] == '-':
player_idx[p] = i - 2
elif i <= len(line) - 3 and line[i + 1] == '-':
player_idx[p] = i + 2
for p, i in player_idx.items():
print(p, '-', data[-1][i])
C#
class Program
{
static void Main(string[] args)
{
char[][] ary = {
//01234567890
("a b c d e f").ToArray(), //0
("| | | | | |").ToArray(), //1
("|-| | |-| |").ToArray(), //2
("| | |-| | |").ToArray(), //3
("| |-| | |-|").ToArray(), //4
("| | |-| | |").ToArray(), //5
("|-| | |-| |").ToArray(), //6
("| | | | | |").ToArray(), //7
("1 2 3 4 5 6").ToArray() //8
};
char input = 'e'; //선택값
int selX = 0; //선택한 Col
int curY = 1; //현재 Row
//선택한 열의 Colum 번호 가져오기
for (int i = 0; i < ary[0].Length; i++)
{
if (input == ary[0][i]) selX = i;
}
//선택한 컬럼의 좌, 연결 확인
int left = 0, right = 0;
char lVal = ' ', rVal = ' ';
Console.WriteLine($"x:{selX} - y:{curY}");
while(curY < ary.Length - 1)
{
//초기화
lVal = ' ';
rVal = ' ';
//좌,우측 위치
left = selX - 1;
right = selX + 1;
if (left > 0) //좌측 컬럼의 '-' 값 확인
lVal = ary[curY][left];
if (right < ary[curY].Length) //우측 커럼의 '-'확인
rVal = ary[curY][right];
if (lVal == '-') //좌측이 '-'값이 있는 경우
{
selX -= 2;
curY += 1;
}
else if (rVal == '-') //우측이 '-'값인 경우
{
selX += 2;
curY += 1;
}
else //좌,우 모두 '-'없는 경우
{
curY += 1;
}
}
Console.WriteLine($"result:{ary[curY][selX]}");
}
}
ladd_str = """a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
"""
B = '@'
ladd = ladd_str.splitlines()
# 문자열 분할 함수를 만들자.
def cut_str(a):
B.join(a)
b = list(a)
while B in b:
b.remove(B)
return b
# ladd는 문자열이 개행으로 나뉘어진 상태이다. 물론 요소값은 공백까지 포함한 문자열이다. ladd[0] == "a b c d e f"
# 사다리의 성분에서 '-' 를 '이음', 'ㅣ' 를 '조각'
# 입력받는 대상은 총 6개이고, 사다리 열에 '이음'이 없는 경우는 6개의 '조각'
for i in range(9):
if 0<i<8:
ladd[i] = cut_str(ladd[i]) # 문자열의 모든 성분을 분할. index를 맞추려면 공백까지도 분할해야함
else:
ladd[i] = ladd[i].split() # 공백 기준으로 문자열 분할. ladd[0] == [a,b,c,d,e,f]
print(ladd)
for i in range(1,8): # 사다리의 성분을 탐색, 조각 사이의 index는 1,3,5,7,9
for j in range(5):
if ladd[i][2*j+1] == '-': # [0][j]과 [0][j+1]을 교환
c = ladd[0][j]
ladd[0][j] = ladd[0][j+1]
ladd[0][j+1] = c
else:
pass
for i in range(6):
print(ladd[0][i] + '-' + ladd[8][i])
저는 python을 사용하였습니다. 문자열을 다루는게 익숙치 않았는데ㅎㅎ.. 좋은 예제네요ㅎㅎ
inputs='''
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
'''
data=inputs.splitlines()
t={'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
for i in range(2,len(data)-1):
for j in range(1,len(data[i].split('|'))-1):
if data[i].split('|')[j] == '-':
t[list(t.keys())[j-1]],t[list(t.keys())[j]]=t[list(t.keys())[j]],t[list(t.keys())[j-1]]
print(t)
#{'a': 5, 'b': 2, 'c': 3, 'd': 6, 'e': 1, 'f': 4}
// ==========================================
String[] st = {
"a b c d e f",
"| | | | | |",
"|-| | |-| |",
"| | |-| | |",
"| |-| | |-|",
"| | |-| | |",
"|-| | |-| |",
"| | | | | |",
"1 2 3 4 5 6" };
String temp = "";
for (int j = 1; j < st[0].length() + 2; j += 2) {
int k = j;
for (int i = 0; i < st.length; i++) {
if (k + 1 < st[i].length() && st[i].substring(k, k + 1).equals("-")) {
k += 2;
} else if (k - 2 > -1 && st[i].substring(k - 2, k - 1).equals("-")) {
k -= 2;
}
temp = st[i].substring(k - 1, k);
}
System.out.println(temp);
}
matrix = []
start = list(input().split())
result = start.copy()
last = []
while True:
k = input()
if k[0] == '1':
last = list(map(int, k.split()))
break
matrix.append(list(k))
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == '-':
temp = result[j//2]
result[j//2] = result[j//2 + 1]
result[j//2 + 1] =temp
for i in range(len(start)):
print(start[i],'-',result.index(start[i])+1 )
def op_ladder(L, ladders):
for s in ladders:
for i in range(1, len(s), 2):
if s[i] == '-':
k = i//2
L[k], L[k+1] = L[k+1], L[k]
L = list(map(lambda x : x + ' - ' + str(L.index(x)+1), L))
L.sort()
print('output:')
for r in L:
print(r)
L = input('input:\n').split()
ladders = []
while True:
s = input()
if s[0].isdigit():
break
ladders.append(s)
op_ladder(L, ladders)
input:
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
output:
a - 5
b - 2
c - 3
d - 6
e - 1
f - 4
파이썬 3.7입니다.
ladder='a b c d e f\n| | | | | |\n|-| | |-| |\n| | |-| | |\n| |-| | |-|\n| | |-| | |\n|-| | |-| |\n| | | | | |\n1 2 3 4 5 6'
lines=ladder.split('\n')
players=lines[0].split(' ')
del lines[0]
rewards=lines[-1].split(' ')
del lines[-1]
for L in lines:
tmp=L.split('|')
bar=[i for i,v in enumerate(tmp) if v=='-']
for b in bar:
rewards[b-1],rewards[b]=rewards[b],rewards[b-1]
for i, v in enumerate(players):
print('{} - {}'.format(v, rewards[i]))
결과
a - 5
b - 2
c - 3
d - 6
e - 1
f - 4
입력값 각 라인 끝에 공백을 붙여야 합니다....
public class 사다리게임 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String[][] ladder = new String[9][12];
for(int i=0; i<9; i++) {
String[] str = scan.nextLine().split("");
for(int j=0; j<str.length; j++) {
ladder[i][j] = str[j];
}
}
int count = 0;
for(int i=0; i<=10; i=i+2) {
for(int j=1;;j=j) {
if(count==0||count==1) {
if(!ladder[j][count+1].equals("-")) {
j++;
}
else if(ladder[j][count+1].equals("-")) {
j++;
count+=2;
}
if(j==8) {
System.out.println(ladder[0][i]+" - "+ladder[j][count]);
count=0;
count=i+2;
break;
}
}
else {
if(ladder[j][count+1].equals(" ")&&ladder[j][count-1].equals(" ")) {
j++;
}
else if(ladder[j][count+1].equals("-")&&ladder[j][count-1].equals(" ")) {
j++;
count+=2;
}
else if(ladder[j][count-1].equals("-")&&ladder[j][count+1].equals(" ")) {
j++;
count-=2;
}
if(j==8) {
System.out.println(ladder[0][i]+" - "+ladder[j][count]);
count=0;
count=i+2;
break;
}
}
}
}
}
}
inp = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
'''
a, *b, c = inp.splitlines()
for col in range(0, len(b[0]), 2):
i = col
for row in range(0, len(b)):
if i < len(b[0])-1 and b[row][i+1] == '-':
i += 2
elif i > 1 and b[row][i-1] == '-':
i -= 2
print('{} - {}'.format(a[col], c[i]))
package ladder_game;
import java.util.Scanner;
public class LadderGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input the numbers of width lines and height lines");
int input_w=in.nextInt(), input_h=in.nextInt(), i, j, m, n;
System.out.println("you inputted "+input_w+" "+input_h);
String[] ladder = new String[input_h+2];
String dummy = new String();
char[][] result = new char[input_w][2];
/*입력받기*/
dummy = in.nextLine();
for(i=0; i<input_h+2; i++)
ladder[i]=in.nextLine();
for(i=0; i<input_w; i++) {
result[i][0] = ladder[0].charAt(2*i);
m=1;
n=i*2;
while(m<=input_h) {
if(n<(input_w-1)*2 && ladder[m].charAt(n+1)=='-') {
n+=2;
m++;
}
else if(n>0 && ladder[m].charAt(n-1)=='-') {
n-=2;
m++;
}
else
m++;
}
result[i][1]=ladder[m].charAt(n);
}
System.out.println("Output:");
for(i=0; i<input_w; i++) {
System.out.println(result[i][0]+"-"+result[i][1]);
}
}
}
Input the numbers of width lines and height
6 7
you inputted 6 7
a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
Output:
a-5
b-2
c-3
d-6
e-1
f-4
l1='''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
print (l1)
l1=l1.split('\n')
l2=[]
for i in range (len(l1)):
temp=[]
for j in range (len(l1[i])):
temp.append(l1[i][j])
l2.append(temp)
i=0
while (i<len(l2[0])):
if l2[0][i]!=' ':
x=i
y=0
print (l2[y][x],'----> ',end='')
while (y<len(l2)-1):
if x==0:
if l2[y][x+1]=='-':
x+=2
y+=1
else:
y+=1
elif x==10:
if l2[y][x-1]=='-':
x-=2
y+=1
else:
y+=1
else:
if l2[y][x-1]=='-':
x-=2
y+=1
elif l2[y][x+1]=='-':
x+=2
y+=1
else:
y+=1
print (l2[y][x])
i+=1
inp="""a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6"""
lst=[list(ln) for ln in inp.split("\n")]
slst=["a","b","c","d","e","f"]
nlst=[0,2,4,6,8,10] #lst에서의 a,b,c,d,e,f의 index
elst=[""]*len(slst)
for idx in nlst:
alpha=slst[int(idx/2)]
for y in range(len(lst)):
if idx-1>=0 and lst[y][idx-1]=="-":
idx=idx-2
elif idx+1<=10 and lst[y][idx+1]=="-":
idx=idx+2
elst[int(idx/2)]=alpha
print(elst)
출력
['e', 'b', 'c', 'f', 'a', 'd']
num = int(input("사다리줄의 개수를 입력:"))
radder = []
for i in range(num):
radder.append(input())
for i in range(0, len(radder[0]), 2):
x = 0
y = i
count = 0
while 1:
if radder[x][y - 1] == "-":
y -= 2
x += 1
count += 1
elif radder[x][(y + 1) % len(radder[0])] == "-":
y += 2
x += 1
count += 1
else:
x += 1
count += 1
if count == 8:
print(radder[0][i] + " - " + radder[x][y])
break
test = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
key_lst = ['a', 'b', 'c', 'd', 'e', 'f']
vl_lst = [1, 2, 3, 4, 5, 6]
test_lst = test.split('\n')
for i in range(1, len(test_lst)-1):
for j in range(1, 10, 2):
if test_lst[i][j] == '-':
t = int(j//2)
key_lst[t], key_lst[t+1] = key_lst[t+1], key_lst[t]
output = dict(zip(key_lst, vl_lst))
output = sorted(output.items())
for i in range(len(output)):
print(f'{output[i][0]} - {output[i][1]}')
inputs = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6
'''
inputs_list = inputs.splitlines()
start = inputs_list[0].split()
end = inputs_list[-1].split()
ladder = inputs_list[1:-1]
for line in ladder:
for i,v in enumerate(line.split("|")):
if v == "-":
end[i-1],end[i] = end[i],end[i-1]
for i,j in zip(start,end):
print("{} - {}".format(i,j))
추천글에 룰루랄라님 참고했습니다
import random
def ladder(x): #랜덤한 사다리 만들기
L = ' '.join([chr(97+e) for e in range(x)])+'\n'
for i in range(5):
line = ''
c = 0
for l in range(x):
if c>0 :
line += '┃ '
c = 0
elif l!=x-1 and random.randint(0,7)<3:
line += '┣━'
c +=1
else :
line += '┃ '
line += '\n'
L += line
L += ' '.join([ str(n) for n in range(1,x+1)])
return L
def last_ladder(x): #사다리 결과값
y = f'{ladder(x)}'.splitlines()
[print(x) for x in y]
a,*b,c = y
c = list(c)
for i in b:
for n,e in enumerate(i):
if e=='━' : c[n-1],c[n+1] = c[n+1],c[n-1]
for d,f in zip(a,c):
if d!=' ': print(f'{d}={f}',end = ' ')
last_ladder(5)
input1='''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
data = input1.split("\n")
data1 = data[0].split()
data2 = data[-1].split()
for line in data[1:-1]:
for i,sw in enumerate(line.split("|")):
if sw == "-":
data2[i-1],data2[i] = data2[i],data2[i-1]
for d1,d2 in zip(data1,data2):
print(d1,"-",d2)
N = list(map(str, input().split()))
check = list(i for i in range(0, len(N)))
M = []
for i in range(7):
M.append(list(map(str,list(input()))))
for j in range(len(M[i])):
if M[i][j] == "-":
h = check[(j+1)//2-1]
check[(j+1)//2-1] = check[(j+1)//2]
check[(j+1)//2] = h
result_check = list(map(int, input().split()))
list(print(N[i], "-", result_check[int(check[i])]) for i in range(len(check)))
players = input("player 입력을 해주세요")
pattern =[]
for i in range(7):
p = input("pattern을 입력해주세요")
pattern.append(p)
num=0
for n in range(0,11,2):
num+=1
step=0
for k in range(len(pattern)):
if n==0:
if pattern[k][n+1] =='-':
n += 2
step +=1
elif n==10:
if pattern[k][n-1] ==' ':
pass
elif pattern[k][n-1] =='-':
n -= 2
step -=1
else :
if pattern[k][n+1] =='-':
n += 2
step +=1
elif pattern[k][n-1] =='-':
n -= 2
step -=1
elif pattern[k][n+1] ==' ' and pattern[k][n-1] ==' ' :
pass
print(players[num-1],'-' ,num+step)
패턴을 한줄씩 배열화하고, 패턴 첫번쨰 줄의 첫번쨰 원소의 앞뒤를 검사했습니다 검사하는 원소를 기준으로 문자'-' 가 있는 위치(좌우)에 따라 step 변수를 증감 하여 목적지를 찾아냈습니다
// Rust
// 사다리 각 line별로 '|'는 제외하고, ' ' 또는 '-'로 인식해서, '-'이면 해당 두 player를 swap해서 구했습니다.
fn ladder() {
let input = "a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6";
let mut ladder = input.lines().map(str::trim);
let mut players: Vec<&str> = ladder.next().unwrap()
.split_whitespace().collect();
for line in ladder {
for (i, v) in line.chars().filter(|&c| c!='|').enumerate() {
if v == '-' { players.swap(i, i+1);}
}
}
println!("{:?}", players);
}
inp = '''a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6'''
fs = first_sequence = inp.split('\n')
cn = column_number = len(fs[0])
rn = row_number = len(inp.split('\n'))
seq = list(fs[0])
for row in range(1, rn-1):
for col in range(1, cn, 2):
if fs[row][col] == '-':
b = seq[col-1]
a = seq[col+1]
seq[col-1] = a
seq[col+1] = b
for col in range(0,cn+1,2):
print(f'{fs[-1][col]} : {seq[col]}')
input = """a b c d e f
| | | | | |
|-| | |-| |
| | |-| | |
| |-| | |-|
| | |-| | |
|-| | |-| |
| | | | | |
1 2 3 4 5 6"""
spl = input.splitlines()
player = list(spl[0])
nums = list(spl[-1])
for i in range(1, len(spl)-1):
for n, p in enumerate(spl[i]):
if n % 2 == 1 and p == '-':
nums[n - 1], nums[n +1] = nums[n +1], nums[n - 1]
for i in range(len(player)):
if i % 2 == 0:
print(player[i], ' - ', nums[i])