출처 : http://www.synapsoft.co.kr/jsp/recruit/17.html

혹시 무엇을 나타낸 그림인지 알아보시겠어요?
하나 더...

네, 맞습니다. 우리의 주인공은 올해에는 애니펑!이라는 게임을 만들어보기로 마음먹었어요!! 하지만 함께 할 파티원을 아직 구하지 못해서, 일단은 핵심 로직이라도 구현해보려 합니다.
누구나 알 것 같은 애니펑! 게임의 규칙을 굳이 써 보자면 아래와 같습니다.
위의 규칙대로 동작하는 프로그램을 작성해주세요.
프로그래밍 언어에 제약은 없지만, 외부 라이브러리는 사용하지 마세요.
입력 형식
아래 예와 같은 5 × 5 숫자 배열을 표준입력으로 읽어들임
2 4 1 2 1
3 4 2 3 3
2 4 1 2 2
4 4 4 1 2
4 2 3 3 2
출력형식
같은 타일들을 모두 처리한 후의 최종 5 × 5 숫자 배열
0 0 0 0 0
2 0 0 0 0
3 0 0 0 0
2 0 0 2 0
4 0 1 3 0
26개의 풀이가 있습니다.
>>>>>>+++++[>+++++[->>[>],>++++++[<-------->-]<+[>+>+<<-]>>[<<+>>-],[-]<[<]<]>>[
>]+>+[<]<<-]>>>[>]>+<<[[->>[>]<+[<]<]>>[[-<+>]>]<+[<]<]>>-[>-]>+[[-]<<[[>>+>>+<<
<<-]<[>>>>+<<<<-]<<[>>+>>+<<<<-]>>[<<+>>-]<<<<[>>>>+>+<<<<<-]>>>>[<<<<+>>>>-]>[>
->-<<-]+>[<[-]>[-]]>[<<[-]>>[-]]<<[<<<[-]+<<[-]+>>>>>>>>[-]+<<<[-]]<<]>>>>>[>[-<
<<<+<+>>>>>]<<<<[->>>>+<<<<]>>>>>>>>>>>>>>>>[-<<<<<<<<<<<<<<<+<+>>>>>>>>>>>>>>>>
]<<<<<<<<<<<<<<<[->>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<]>>>>>>>>>>>>>>>>>>>>>>>>>>>[-<
<<<<<<<<<<<<<<<<<<<<<<<<<+<+>>>>>>>>>>>>>>>>>>>>>>>>>>>]<<<<<<<<<<<<<<<<<<<<<<<<
<<[>>>>>>>>>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-]+<[-<-<->>]<[>>[-]<<[-
]]<[>>>[-]<<<[-]]>>>[->[-]+>>>>>>>>>>>>[-]+>>>>>>>>>>>>[-]+<<<<<<<<<<<<<<<<<<<<<
<<<<]>[<<<<<<<<+>>>>>>>>-]>[<<<<<<<<+>>>>>>>>-]>]<<<<<<<<<[[>>>>>>>>+<<<<<<<<-]<
]>>>>>>>>>[>]>+++++[-<<[<]>[[<+<+>>-]+<-[>-<[-]]>[->>>>>>>>>>>>[<<<<<<<<<<<<+<+>
>>>>>>>>>>>>-]<<<<<<<<<<<<[->>>>>>>>>>>>+<<<<<<<<<<<<]<[[-]>>>>>>>>>>>>>[<<<<<<<
<<<<<<<+>>>>>>>>>>>>>>-]+<<<<<<<<<<<<<<->]>]>[<<+>>-]>]<<<[[>>+<<-]<]>>>[>]>]<<[
[>>+>>+<<<<-]<[>>+>>+<<<<-]>>[->-<]>[[>]>+<<[<]>[-]]>>[-]<[<+>-]<[>+>+<<-]<<<<]>
>>>>[>]>]<<[[<]<+++++[>>[>]++++++[<++++++++>-]<-.[-]<[-]++++[>++++++++<-]>.<<[<]
<-]>>[>]<+++++++++.<-<]
$ cat input | bf anipung.b
0 0 0 0 0
2 0 0 0 0
3 0 0 0 0
2 0 0 2 0
4 0 1 3 0
#터뜨리고 채우는 함수(확장성 확보, 이후에 블럭이 터지는 다른조건을 추가할 수 있도록)
def peung(board):
while(peung_chain(board)):
filled_board(board)
#3개 이상 연속되어 있는 블럭을 터뜨리는 함수
def peung_chain(board):
peung_list = []
flag = 0 #3개 이상 연속되는 블럭이 있었는지를 체크하는 플래그
for i in range(5):
for j in range(5):
if board[i][j] != 0:
#같은 열에 3개 이상 같은 블럭이 반복되는지.
if j<3 and (board[i][j] == board[i][j+1] == board[i][j+2]):
flag =1
k = j
while (k<5 and (board[i][j] == board[i][k])):
peung_list.append((i,k))
k+=1
#같은 행에 3개 이상 같은 블럭이 반복되는지
if i<3 and (board[i][j] == board[i+1][j] == board[i+2][j]):
flag = 1
k = i
while (k<5 and (board[i][j] == board[k][j]) ):
peung_list.append((k,j))
k+=1
for item in peung_list:
board[item[0]][item[1]] = 0
if flag == 1:
return True
else: return False
#빈공간 채우기 함수
def filled_board(board):
#두번째 행 부터 원소가 0이고 이전 행의 같은 열 원소가 0이 아닌 경우 내리기
for i in range(1,5):
for j in range(5):
k=i
while(k> 0):
if board[k][j] == 0 and board[k-1][j] != 0:
board[k][j] = board[k-1][j]
board[k-1][j] = 0
k-=1
else: break
#보드 출력 함수
def print_board(board):
for i in range(5):
print("{0} {1} {2} {3} {4}".format(board[i][0], board[i][1], board[i][2], board[i][3], board[i][4]))
print("")
def main():
board = [[2, 4, 1, 2, 1], [3, 4, 2, 3, 3], [2, 4, 1, 2, 2], [4, 4, 4, 1, 2], [4, 2, 3, 3, 2]]
peung(board)
print_board(board)
main()
# diagonal 기준으로 연결성을 확인해서 기록합니다. 이 때 row방향과 column방향은 조사 방식에 차이가 없으므로 같은 함수를 이용합니다.
## 이후 column 기준으로 collapse 합니다.
def cslice(arr, k): # array columnwise slicing
col = [arr[i][k] for i in range(5)]
return col
def putcol(arr, vec, k): # array columnwise filling
for i in range(5):
arr[i][k] = vec[i]
def diagonal_inspector(arr): # global inspector
indicator = [[False]*5 for k in range(5)]
for k in range(5):
row_ind = local_inspector(arr[k]) # check row
indicator[k] = [a or b for a, b in zip(indicator[k], row_ind)]
col_ind = local_inspector(cslice(arr, k)) # check column
col_ind = [a or b for a, b in zip(cslice(indicator, k), col_ind)]
putcol(indicator, col_ind, k)
collapse = check_collapse(indicator) # determine collapse
return indicator, collapse
def local_inspector(vec): # vectorwise local inspector
local_indicator = [False]*5
for i in range(3):
num = vec[i]
if num == 0:
continue
if num == vec[i + 1] == vec[i + 2]:
local_indicator[i:i+3] = [True]*3
if (i < 2) and (num == vec[i + 3]):
local_indicator[i + 3] = True
if (i < 1) and (num == vec[i + 4]):
local_indicator[i + 4] = True
else:
continue
return local_indicator
def check_collapse(indicator):
for i in range(5):
for j in range(5):
if indicator[i][j] == True:
return True
return False
def collapse_col(col, col_indicator): # columnwise collapse
t = []
for i in range(5):
if col_indicator[i] == False:
t.append(col[i])
if len(t) < 5:
ccol = [0]*(5-len(t))
ccol.extend(t)
return ccol
else:
return t
def show_array(arr): # show array
for i in range(5):
print("{0} {1} {2} {3} {4}".format(arr[i][0], arr[i][1], arr[i][2], arr[i][3], arr[i][4]))
def anypfung(arr):
indicator, collapse = diagonal_inspector(arr)
while collapse:
for i in range(5):
putcol(arr, collapse_col(cslice(arr,i),cslice(indicator,i)), i)
indicator, collapse = diagonal_inspector(arr)
show_array(arr)
REP = [[2, 4, 1, 2, 1], [3, 4, 2, 3, 3], [2, 4, 1, 2, 2], [4, 4, 4, 1, 2], [4, 2, 3, 3, 2]]
anypfung(REP)
`
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE BlockArguments #-}
import Data.Array
import Data.List
import Data.Tuple
import Data.Function
import Control.Monad
groupOn f = groupBy ((==) `on` f)
limit = until =<< ((==) =<<)
horizontal = groupOn fst . range . bounds
vertical = transpose <$> horizontal
bothways = horizontal <> vertical
through ray genAssoc ar = ar // (ray ar >>= genAssoc (ar!))
pop = through bothways \f ->
fmap (,0) . join . filter ((>=3) . length) . groupOn f
pulldown = through vertical \f ->
zip <*> sortOn (/=0) . fmap f
anipung = limit $ pulldown . pop
render ar = horizontal ar >>= (>>= (show . (ar!)) <> const " ") <> const "\n"
parse = listArray ((1,1), (5,5)) . fmap read . words
main = putStr . render . anipung . parse =<< getContents
adjacent3 함수로 가로 또는 세로로 동일한 타일 3개가 연속되면 각 타일의 위치를 파악합니다. pushtobottom 함수로 현재 0 위에 0이 아닌 숫자가 써진 타일이 위치하면 각 타일의 위치를 파악합니다. adjacent3 에서 반환되는 값이 빈 리스트 일 때까지, 입력받은 리스트에서 연속한 3개를 0으로 바꾸고 매번 pushtobottom에 속한 타일을 아래 타일과 바꿔 pushtobottom이 빈 리스트가 될 때까지 시행합니다.
def anipang(a):
def adjacent3(a):
result = list()
for i in range(len(a)):
for j in range(len(a[0]) - 2):
if a[i][j] == a[i][j + 1] == a[i][j + 2] != 0:
result.append((i, j)); result.append((i, j + 1)); result.append((i, j + 2))
for i in range(len(a) - 2):
for j in range(len(a[0])):
if a[i][j] == a[i + 1][j] == a[i + 2][j] != 0:
result.append((i, j)); result.append((i + 1, j)); result.append((i + 2, j))
return sorted(list(set(result)))
def pushtobottom(a):
result = list()
for i in range(len(a) - 1):
for j in range(len(a[0])):
if a[i + 1][j] == 0 and a[i][j] != 0:
result.append((i, j))
return result
b = adjacent3(a)
while b:
for i in b:
a[i[0]][i[1]] = 0
c = pushtobottom(a)
while c:
for j in c:
(a[j[0]][j[1]], a[j[0]+1][j[1]]) = (a[j[0]+1][j[1]], a[j[0]][j[1]])
c = pushtobottom(a)
b = adjacent3(a)
return a
a = list()
while 1:
n = input()
if n == '':
break
else:
a.append(list(map(int, n.split())))
for i in anipang(a):
for j in i:
print(j, end= ' ')
print('\n')
Ruby
mark = ->(t) { t.map {|r| r.chunk {|_|_}.sum([]) {|_,g| g[2] ? g.fill(0) : g}}}
pung = ->(tile = (1..5).map { gets.split.map &:to_i }.transpose) do
rslt = mark[tile].zip(mark[tile.transpose].transpose).
map {|r1,r2| r1.zip(r2).map {|a,b| a & b}.partition(&:zero?).sum([])}
tile == rslt ? puts(rslt.transpose.map {|row| row.join(' ')}) : pung[rslt]
end
Test
$stdin = StringIO.new("2 4 1 2 1\n" +
"3 4 2 3 3\n" +
"2 4 1 2 2\n" +
"4 4 4 1 2\n" +
"4 2 3 3 2\n")
expect { pung.call }.to output("0 0 0 0 0\n" +
"2 0 0 0 0\n" +
"3 0 0 0 0\n" +
"2 0 0 2 0\n" +
"4 0 1 3 0\n").to_stdout
파이썬입니다. 문자열 슬라이싱이 너무 지저분한데 다른 방법을 잘 모르겠네요 ...
def aniPung(text):
def p_aniPung(arr):
check = ['11111','11111','11111','11111','11111']
for row in range(5):
for i in range(3):
if arr[row][i] == arr[row][i+1] == arr[row][i+2] != '0':
check[row] = check[row][:i] + "000" + check[row][i+3:]
for col in range(5):
for i in range(3):
if arr[i][col] == arr[i+1][col] == arr[i+2][col] != '0':
check[i] = check[i][:col] + "0" + check[i][col+1:]
check[i+1] = check[i+1][:col] + "0" + check[i+1][col+1:]
check[i+2] = check[i+2][:col] + "0" + check[i+2][col+1:]
if check != ['11111','11111','11111','11111','11111']:
for r in range(5):
for l in range(5):
if check[r][l] == "0":
arr[r] = arr[r][:l] + "0" + arr[r][l+1:]
for r in range(5):
for l in range(5):
check[r] = check[r][:l] + arr[l][r] + check[r][l+1:]
check[r] = check[r].replace("0","").zfill(5)
for r in range(5):
for l in range(5):
arr[r] = arr[r][:l] + check[l][r] + arr[r][l+1:]
aniPung(arr)
else:
for r in arr:
print(r)
def textToArr(t):
st=""
ar=[]
for c in t:
if c != " " and "\n":
st = st + c
#print(st)
if len(st) >= 5:
ar.append(st)
st = ""
p_aniPung(ar)
textToArr(text)
aniPung("2 4 1 2 1 \
3 4 2 3 3 \
2 4 1 2 2 \
4 4 4 1 2 \
4 2 3 3 2")
input_keys = [[2, 4, 1, 2, 1],[3, 4, 2, 3, 3],[2, 4, 1, 2, 2],[4, 4, 4, 1, 2],[4, 2, 3, 3, 2]]
#input_keys = [[1,4,2,4,1],[2,1,2,4,3],[2,1,3,4,3],[4,1,4,1,3],[2,4,3,4,1]]
locationx = []
locationy = []
location_width = {}
location_high = {}
count_sameline = 0
input_keys_high = []
check1 = 0
check2 = 0
test = 0
first = 0
#--------------------------------------------------------------------------------------------------
while 1:
#가로의 3개이상 붙어있는 같은수 찾는 부분
for i in range(0,5):
for k in range(1,5):
if input_keys[i][k] == input_keys[i][k-1] and input_keys[i][k] != 0:
test = input_keys[i][k-1]
if count_sameline == 0:
locationx.append(k-1)
locationx.append(k)
count_sameline += 1
if count_sameline >= 2:
#중복수가 나올때 오류를 해결하기위한 구문
if test != input_keys[i][locationx[0]]:
locationx.remove(k)
location_width[i] = locationx
locationx = []
count_sameline = 0
if location_width == {}:
check1 = 1
#세로의 3개이상 붙어있는 같은수 찾는 부분
for j in range(0,5):
for t in range(1,5):
if input_keys[t][j] == input_keys[t-1][j] and input_keys[t][j] != 0:
test = input_keys[t][j]
if count_sameline == 0:
locationy.append(t-1)
locationy.append(t)
count_sameline += 1
if count_sameline >= 2:
if test != input_keys[locationy[0]][j]:
locationy.remove(t)
if len(locationy) <= 2:
locationy = []
if locationy != []:
location_high[j] = locationy
locationy = []
count_sameline = 0
if location_high == {}:
check2 = 1
for i in range(0,5):
print(input_keys[i])
print('----------')
print('세로',location_high)
print('가로',location_width)
#3개 이상 연결된 숫자가 없다면 반복문 탈출
if check1 == 1 and check2 == 1:
break
# 같은수 3줄이상 이어진 부분 0으로 치환
for o in location_width.keys():
for j in location_width[o]:
input_keys[o][j] = 0
for o in location_high.keys():
for j in location_high[o]:
input_keys[j][o] = 0
# 사잇공간 채우기
for i in range(0,5):
for k in range(0,5):
input_keys_high.append(input_keys[k][i])
index = input_keys_high.count(0)
for o in range(0,5):
temp = list(filter(lambda x:x > 0 , input_keys_high))
for f in range(0,index):
temp.insert(0,0)
for h in range(0,5):
input_keys[h][i] = temp[h]
temp = []
input_keys_high = []
#프로그램 초기화
locationx = []
locationy = []
location_width = {}
location_high = {}
count_sameline = 0
input_keys_high = []
check1 = 0
check2 = 0
test = 0
first = 0
#--------------------------------------------------------------------------------------------------
#결과값 출력
for i in range(0,5):
print(input_keys[i])
def overturnList(argList):
argListTmp = list(zip(argList[0], argList[1], argList[2], argList[3], argList[4]))
return [ list(argListTmp[i]) for i in range(len(argListTmp[0])) ]
def pung(argList):
argListTmp = [ [ ]*5 for i in range(0, 5) ]
argListTmp = list(argList)#리스트 값 복사 http://henry.precheur.org/python/copy_list
for i in range(0, 5):
if (len(set(argListTmp[i][0:5])) == 1) and not(0 in argListTmp[i][0:5]):
argListTmp[i][0:5] = [ -1, -1, -1, -1, -1 ]
if (len(set(argListTmp[i][0:4])) == 1) and not(0 in argListTmp[i][0:4]):
argListTmp[i][0:4] = [ -1, -1, -1, -1 ]
if (len(set(argListTmp[i][1:5])) == 1) and not(0 in argListTmp[i][1:5]):
argListTmp[i][1:5] = [ -1, -1, -1, -1 ]
if (len(set(argListTmp[i][0:3])) == 1) and not(0 in argListTmp[i][0:3]):
argListTmp[i][0:3] = [ -1, -1, -1 ]
if (len(set(argListTmp[i][1:4])) == 1) and not(0 in argListTmp[i][1:4]):
argListTmp[i][1:4] = [ -1, -1, -1 ]
if (len(set(argListTmp[i][2:5])) == 1) and not(0 in argListTmp[i][2:5]):
argListTmp[i][2:5] = [ -1, -1, -1 ]
return argListTmp
matrix = []
for i in range(5):
matrix.append(list(map(int, input().split())))
matrixTmp = [[]*5 for i in range(0, 5)]
isValidCalc = True
while isValidCalc:
matrixTmp = list(matrix)
verticalMatrix = overturnList(matrixTmp)
verticalMatrix = pung(verticalMatrix)
verticalMatrix = overturnList(verticalMatrix)
matrix = pung(matrix)
isValidCalc = False
for i in range(0, 5):
for j in range(0, 5):
if (matrix[i][j] == -1) or (verticalMatrix[i][j] == -1):
matrix[i][j] = -1
isValidCalc = True
matrixTmp = list(matrix)
verticalMatrix = overturnList(matrixTmp)
for i in range(0, 5):
if -1 in verticalMatrix[i]:
cnt = verticalMatrix[i].count(-1)
for j in range(0, cnt):
verticalMatrix[i].remove(-1)
verticalMatrix[i].insert(0, 0)
matrix = overturnList(verticalMatrix)
print("최종")
for i in range(0, 5):
print(matrix[i])
/**
*
*/
import java.util.HashSet;
import java.util.Set;
/**
* @author
* @see http://codingdojang.com/scode/583
*
*/
public class Problem583 {
static final int SIZE = 5;
public static void main(String[] args) {
final String[] INPUT = {
"2 4 1 2 1",
"3 4 2 3 3",
"2 4 1 2 2",
"4 4 4 1 2",
"4 2 3 3 2"};
final String[][] tiles = new String[SIZE][SIZE];
for (int y=0; y<SIZE; y++) {
tiles[y] = INPUT[y].split(" ");
}
while (explode(tiles) > 0) {
trim(tiles);
}
print(tiles);
}
private static int explode(String[][] tiles) {
Set<Match> matched = new HashSet<>();
// 옆으로 비교
for (int y=0; y<SIZE; y++) {
for (int x=0; x<SIZE; x++) {
if (x + 2 >= SIZE) {// 3개까지 비교할 수 없음
break;
}
if (!tiles[y][x].equals("0") &&
tiles[y][x].equals(tiles[y][x+1]) && tiles[y][x].equals(tiles[y][x+2])) {
matched.add(new Match(x, y));
matched.add(new Match(x+1, y));
matched.add(new Match(x+2, y));
}
}
}
// 아래로 비교
for (int x=0; x<SIZE; x++) {
for (int y=0; y<SIZE; y++) {
if (y + 2 >= SIZE) {// 3개까지 비교할 수 없음
break;
}
if (!tiles[y][x].equals("0") &&
tiles[y][x].equals(tiles[y+1][x]) && tiles[y][x].equals(tiles[y+2][x])) {
matched.add(new Match(x, y));
matched.add(new Match(x, y+1));
matched.add(new Match(x, y+2));
}
}
}
for (Match match : matched) {
tiles[match.y][match.x] = "0";
}
return matched.size();
}
/**
* 빈공간 내리기
* @param tiles
*/
private static void trim(String[][] tiles) {
for (int x=0; x<SIZE; x++) {
for (int y=SIZE-1; y>=0; y--) {
if (tiles[y][x].equals("0")) {
String nonZeroVal = getNonZeroCeil(tiles, x, y-1);
if (nonZeroVal != null) {
tiles[y][x] = nonZeroVal;
}
}
}
}
}
/**
* 위쪽으로 "0"이 아닌 값을 가져옴
* @param tiles
* @param x
* @param y
* @return
*/
private static String getNonZeroCeil(String[][] tiles, int x, int y) {
for (int tmp=y; tmp>=0; tmp--) {
if (!tiles[tmp][x].equals("0")) {
String val = tiles[tmp][x];
tiles[tmp][x] = "0";
return val;
}
}
return null;
}
private static class Match {
final int x;
final int y;
private Match(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return x * 10 + y;
}
@Override
public boolean equals(Object obj) {
Match other = (Match)obj;
return x == other.x && y == other.y;
}
}
private static void print(String[][] tiles) {
for (int y=0; y<SIZE; y++) {
System.out.println(String.join(" ", tiles[y]));
}
}
}
Swift입니다.
import Foundation
var testBoard = [ [2, 4, 1, 2, 1],
[3, 4, 2, 3, 3],
[2, 4, 1, 2, 2],
[4, 4, 4, 1, 2],
[4, 2, 3, 3, 2]]
func printBoard(_ board:[[Int]]) {
for line in board {
print(line.reduce("", {$0 + String($1) + " "}))
}
}
func dropItems(_ givenBoard:[[Int]]) -> [[Int]] {
var board = givenBoard
for x in 0...4 {
var column = [Int]()
for i in stride(from: 4, to: -1, by: -1) {
let item = board[i][x]
if item != 0 {
board[i][x] = 0
column.append(item)
}
}
for i in 0..<column.count {
board[5 - i - 1][x] = column[i]
}
}
return board
}
func find3AdjacentItems(_ board: [[Int]], _ x: Int, _ y: Int) -> [(x: Int, y: Int)] {
var itemsToBeDeleted = [(x:Int, y:Int)]()
let targetItem = board[y][x]
if targetItem != 0 {
if x < 3 { // Horizontal - Move Right
if board[y][x + 1] == targetItem && board[y][x + 2] == targetItem {
for i in x...4 {
if board[y][i] == targetItem {
itemsToBeDeleted.append((x: i, y: y))
}
}
}
}
if y < 3 { // Vertical - Move Down
if board[y + 1][x] == targetItem && board[y + 2][x] == targetItem {
for i in y...4 {
if board[i][x] == targetItem {
itemsToBeDeleted.append((x: x, y: i))
}
}
}
}
}
return itemsToBeDeleted
}
func processBoard(_ givenBoard:[[Int]]) -> [[Int]] {
var board = givenBoard
var foundItems = [(x: Int, y:Int)]()
repeat {
foundItems.removeAll(keepingCapacity: true)
for x in 0...2 {
for y in 0...4 {
foundItems += find3AdjacentItems(board, x, y)
}
}
for x in 0...4 {
for y in 0...2 {
foundItems += find3AdjacentItems(board, x, y)
}
}
if foundItems.count > 0 {
for (dx, dy) in foundItems {
board[dy][dx] = 0
}
board = dropItems(board)
}
} while foundItems.count > 0
return board
}
printBoard( processBoard(testBoard) )
결과는...
0 0 0 0 0
2 0 0 0 0
3 0 0 0 0
2 0 0 2 0
4 0 1 3 0
풀이는 아니지만 c# 으로 옮겨봤습니다. 리스트를 2차원으로 만드는 방법을 잘 알고있다면 요긴하게 쓸곳이 많겠네요
public static void Test1()
{
//int[,] iPlate = new int[5, 5] { { 2, 4, 1, 2, 1 }, { 3, 4, 2, 3, 3 }, { 2, 4, 1, 2, 2 }, { 4, 4, 4, 1, 2 }, { 4, 2, 3, 3, 2 } };
int[,] iPlate = new int[5, 5];
Random random = new Random();
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++) iPlate[i, j] = random.Next(1, 4);
}
for (int i = 0; i < 5; i++) Console.WriteLine($"Line {(i+1).ToString()} : {iPlate[i, 0]} {iPlate[i, 1]} {iPlate[i, 2]} {iPlate[i, 3]} {iPlate[i, 4]}");
List<string> lFinalList = new List<string>();
int k = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (j < 3 && (iPlate[i, j] == iPlate[i, j+1]) && (iPlate[i, j+1] == iPlate[i, j + 2]))
{
k = j;
while (k < 5 && (iPlate[i,j] == iPlate[i,k]))
{
lFinalList.Add(i.ToString() + k.ToString());
k++;
}
}
if (i < 3 && (iPlate[i, j] == iPlate[i+1, j]) && (iPlate[i + 1, j] == iPlate[i+2,j]))
{
k = i;
while (k < 5 && (iPlate[i, j] == iPlate[k, j]))
{
lFinalList.Add(k.ToString() + j.ToString());
k++;
}
}
}
}
foreach (var item in lFinalList) iPlate[Convert.ToInt32(item.Substring(0,1)), Convert.ToInt32(item.Substring(1, 1))] = 0;
Console.WriteLine("====================");
for (int i = 0; i < 5; i++) Console.WriteLine($"Line {(i+1).ToString()} : {iPlate[i, 0]} {iPlate[i, 1]} {iPlate[i, 2]} {iPlate[i, 3]} {iPlate[i, 4]}");
Console.ReadKey();
}
// AniPang.cpp: 콘솔 응용 프로그램의 진입점을 정의합니다.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void shift(int **matrix) {
for (int i = 0; i < 5; i++) {
for (int y = 4; y > 0; y--) {
for (int x = 0; x < 5; x++) {
if (matrix[y][x] == 0) {
matrix[y][x] = matrix[y - 1][x];
matrix[y - 1][x] = 0;
}
}
}
}
}
void gameScreen(int **matrix) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << matrix[i][j] << " ";
}cout << "\n";
}
cout << "\n";
}
void pang(int **matrix) {
for (int i = 0; i < 2; i++) { // 한번 더 돌리면서 확인해준다
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 5; x++) {
//가로펑
if (x < 3) {
if (matrix[y][x] == matrix[y][x + 1] && matrix[y][x] == matrix[y][x + 2] && matrix[y][x] != 0) {
matrix[y][x] = 0;
matrix[y][x + 1] = 0;
matrix[y][x + 2] = 0;
shift(matrix);
gameScreen(matrix);
}
}
//세로펑
if (y < 3) {
if (matrix[y][x] == matrix[y + 1][x] && matrix[y][x] == matrix[y + 2][x] && matrix[y][x] != 0) {
matrix[y][x] = 0;
matrix[y + 1][x] = 0;
matrix[y + 2][x] = 0;
shift(matrix);
gameScreen(matrix);
}
}
}
}
}
}
int main()
{
int **matrix = new int*[5];
for (int i = 0; i < 5; i++) {
matrix[i] = new int[5];
}
int line0[5] = {2,4,1,2,1};
int line1[5] = {3,4,2,3,3};
int line2[5] = {2,4,1,2,2};
int line3[5] = {4,4,4,1,2};
int line4[5] = {4,2,3,3,2};
matrix[0] = line0;
matrix[1] = line1;
matrix[2] = line2;
matrix[3] = line3;
matrix[4] = line4;
gameScreen(matrix);
pang(matrix);
system("pause");
return 0;
}
c++로 이차원매트리스를 parameter로 이것보다 더 효율적으로 받는 방법이 있으면 알려주세요!
//•타일판은 5 × 5
//•타일 종류는 1 ~4의 네 가지
//•가로나 세로로 3개 이상 같은 타일이 연속될 경우 펑!사라지고, 그 자리에는 위쪽의 타일들이 내려와서 메꿉니다.
//•내려오면서 비게 된 자리는 0으로 채워집니다
#include "stdafx.h"
#include <iostream>
#define X 9
#define MR 7
#define MC 7
//j
int map[MR][MC] = { { X, X, X, X, X, X, X },
/*i*/ { X, 2, 4, 1, 2, 1, X },
{ X, 3, 4, 2, 3, 3, X },
{ X, 2, 4, 1, 2, 2, X },
{ X, 4, 4, 4, 1, 2, X },
{ X, 4, 2, 3, 3, 2, X },
{ X, X, X, X, X, X, X } };
void get_down()
{
for (int j = 1; j < MC-1; j++)
{
for (int i = 1; i < MR-1; i++)
{
if (map[i+1][j] == 0)
{
map[i+1][j] = map[i][j];
map[i][j] = 0;
}
}
}
}
void display()
{
for (int i = 1; i < MR - 1; i++)
{
for (int j = 1; j < MC - 1; j++)
{
std::cout << map[i][j] << " ";
}
std::cout << "\n";
}
}
void find_width()
{
int cnt = 0, cntnum=0;
int i = 1, j = 1;
for (i = 1; i < MR-1; i++)
{
for (j = 1; j < MC-1; j++)
{
if ((map[i][j+1] == map[i][j]) && (map[i][j+2] == map[i][j]) && map[i][j] != 0 && map[i][j] != -9)
{
for (int k = j; k < j + 3; k++) map[i][k] = 0;
i = 1, j = 1;
}
get_down();
}
}
}
void find_length()
{
int cnt = 0, cntnum = 0;
int i = 1, j = 1;
for (j = 1; j < MC-1; j++)
{
for (i = 1; i < MR-1; i++)
{
if ((map[i + 1][j] == map[i][j]) && (map[i + 2][j] == map[i][j]) && map[i][j]!=0 && map[i][j]!=-9)
{
for (int k = i; k < i + 3; k++) map[k][j] = 0;
i = 1, j = 1;
}
get_down();
}
}
}
int main()
{
for (int i = 0; i < 5; i++)
{
find_length();
find_width();
}
display();
return 0;
}
제가 푼 풀이가 맞는진 모르겠지만 답은나왔네요..ㅎㅎㅎ
C++ version
#include "stdafx.h"
#include <iostream>
class AnyPang
{
public:
void SetInitialTile();
void Play();
void ShowResult();
private:
bool CheckHorizontal();
bool RemoveHorizontalIfNeed(int row, int start, int end);
void RemoveAndStuffHorizontalLine(int row, int start, int end);
bool CheckVertical();
bool RemoveVerticalIfNeed(int row, int start, int end);
void RemoveAndStuffVerticalLine(int column, int start, int end);
bool IsPangPangPang(int start, int end);
bool ContinueIfInvalidCell(int row, int column);
int tile[5][5] = { 0, };
};
int main()
{
AnyPang pang;
pang.SetInitialTile();
pang.Play();
pang.ShowResult();
return 0;
}
void AnyPang::SetInitialTile()
{
std::cout << "input 5 x 5 square number for each slot" << std::endl;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
std::cin >> tile[i][j];
}
}
}
void AnyPang::Play()
{
bool found = true;
// 더 이상 "팡팡팡"을 찾을 수 없을 때 까지 반복합니다.
while (found)
{
found = false;
found |= CheckHorizontal();
found |= CheckVertical();
}
}
bool AnyPang::CheckHorizontal()
{
int candidate, to;
// 마지막 줄 부터...
for (int row = 4; row >= 0; row--)
{
candidate = 4;
to = 4;
for (int column = 4; column >= 0; column--)
{
// 0 이 나오면 건너뜁니다.
if (ContinueIfInvalidCell(row, column))
{
// 건너 뛰기 전에 한번 체크해보고...
if (RemoveHorizontalIfNeed(row, candidate, to))
{
return true;
}
// 후보 열을 현재 열로 변경.
candidate = column;
continue;
}
// 동일한 숫자가 나오면 column을 저장합니다.
if (tile[row][candidate] == tile[row][column]) {
to = column;
if (column != 0)
{
continue;
}
}
// 가로 라인 조건이 충족되었는지 확인하고 제거합니다.
if (RemoveHorizontalIfNeed(row, candidate, to))
{
return true;
}
// 후보 열을 현재 열로 변경.
candidate = column;
}
}
return false;
}
bool AnyPang::ContinueIfInvalidCell(int row, int column)
{
return tile[row][column] == 0;
}
bool AnyPang::RemoveHorizontalIfNeed(int row, int start, int end)
{
if (IsPangPangPang(start, end))
{
RemoveAndStuffHorizontalLine(row, start, end);
return true;
}
return false;
}
// 3개 이상 연속되는지 확인
bool AnyPang::IsPangPangPang(int start, int end)
{
return start - end >= 2;
}
void AnyPang::RemoveAndStuffHorizontalLine(int row, int start, int end)
{
// 위에서 한칸씩 땡겨줍니다.
while (row > 0)
{
for (int j = start; j >= end; j--)
{
tile[row][j] = tile[row-1][j];
}
row--;
}
// 제일 윗줄은 0으로 채워줍니다.
for (int j = start; j >= end; j--)
{
tile[row][j] = 0;
}
}
bool AnyPang::CheckVertical()
{
int candidate, to;
// 가장 오른쪽 열 부터...
for (int column = 4; column >= 0; column--)
{
candidate = 4;
to = 4;
// 가장 마지막 줄 부터...
for (int row = 4; row >= 0; row--)
{
// 0 이 나오면 건너뜁니다.
if (ContinueIfInvalidCell(row, column))
{
// 건너 뛰기 전에 한번 체크해보고...
if (RemoveVerticalIfNeed(column, candidate, to))
{
return true;
}
// 후보 행을 현재 행으로 변경.
candidate = row;
continue;
}
// 동일한 숫자가 나오면 row를 저장합니다.
if (tile[candidate][column] == tile[row][column]) {
to = row;
if (row != 0)
{
continue;
}
}
// 세로 라인 조건이 충족되었는지 확인하고 제거합니다.
if (RemoveVerticalIfNeed(column, candidate, to))
{
return true;
}
// 후보 행을 현재 행으로 변경.
candidate = row;
}
}
return false;
}
bool AnyPang::RemoveVerticalIfNeed(int column, int start, int end)
{
if (IsPangPangPang(start, end))
{
RemoveAndStuffVerticalLine(column, start, end);
return true;
}
return false;
}
void AnyPang::RemoveAndStuffVerticalLine(int column, int start, int end)
{
// 연속된 세로 줄 바로 위 행
int avobe = 0;
if (end > 0)
{
avobe = end - 1;
}
// 아래서부터 채워줍니다.
while (avobe >= 0)
{
tile[start][column] = tile[avobe][column];
start--; avobe--;
}
// 남은 윗 쪽은 다 0으로 채웁니다.
while (start >= 0)
{
tile[start][column] = 0;
start--;;
}
}
void AnyPang::ShowResult()
{
for (int i = 0; i < 5; i++)
{
std::cout << std::endl;
for (int j = 0; j < 5; j++)
{
std::cout << " " << tile[i][j] << " ";
}
std::cout << std::endl;
}
}
def anipang(board:Array[Array[Int]]):Array[Array[Int]] = {
def reArange(set: Set[(Int, Int)]){
var bool = false
for((a, b) <- set){
board(a)(b) = 0
}
for(col <- 0 until board(0).length){
var index = board.length - 1
for(row <- board.length - 1 to 0 by -1){
if(board(row)(col) != 0){
var temp = board(row)(col)
board(row)(col) = board(index)(col)
board(index)(col) = temp
index -= 1
}
}
}
}
var bool = true
while(bool){
var set = Set[(Int, Int)]()
for(i <- 0 until board.length; j <- 0 until board(i).length){
var row = i
var col = j
// 세로 확인
while(row < board.length && board(i)(j) != 0 && board(row)(j) == board(i)(j)) row += 1
// 가로 확인
while(col < board(i).length && board(i)(j) != 0 && board(i)(col) == board(i)(j)) col += 1
if(row - i >= 3){
(i until row).foreach{ v => set += Tuple2(v, j)}
}
if(col - j >= 3){
(j until col).foreach{ v => set += Tuple2(i, v)}
}
}
reArange(set)
if(set.isEmpty) bool = false
}
board
}
anipang(Array(
Array(2, 4, 1, 2, 1),
Array(3, 4, 2, 3, 3),
Array(2, 4, 1, 2, 2),
Array(4, 4, 4, 1, 2),
Array(4, 2, 3, 3, 2)
)).map(_.toList).toList.foreach(v => v.mkString(" "))
#include "stdafx.h"
#include <iostream>
using namespace std;
void check_garo(int board[][5],bool &garo)
{
for (int i = 0; i < 5; i++)
{
for (int j = 1; j < 4; j++)
{
if (board[i][j - 1] == board[i][j] && board[i][j + 1] == board[i][j]&&board[i][j-1]!=0)
{
if (i == 0)
{
board[i][j - 1] = 0, board[i][j] = 0, board[i][j + 1] = 0;
garo = true;
return;
}
else
{
for (int k = i; k > 0; k--)
{
board[k][j - 1] = board[k - 1][j - 1], board[k - 1][j - 1] = 0;
board[k][j] = board[k - 1][j], board[k - 1][j] = 0;
board[k][j + 1] = board[k - 1][j + 1], board[k - 1][j + 1] = 0;
}
garo = true;
return;
}
}
}
}
}
void check_sero(int board[][5],bool &sero)
{
for (int i = 0; i < 5; i++)
{
for (int j = 1; j < 4; j++)
{
if (board[j-1][i] == board[j][i] && board[j+1][i] == board[j][i]&&board[j-1][i]!=0)
{
if (j - 3 >= 0)
{
board[j - 1][i] = 0;
board[j][i] = 0;
board[j + 1][i] = 0;
board[j + 1][i] = board[j - 2][i];
board[j][i] = board[j - 3][i];
board[j - 2][i] = 0;
board[j - 3][i] = 0;
}
else
{
board[j - 1][i] = 0;
board[j][i] = 0;
board[j + 1][i] = 0;
}
sero = true;
}
}
}
}
void Draw_Game(int board[][5])
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
cout << board[i][j];
cout << endl;
}
cout << endl;
}
int main()
{
bool garo, sero;
int board[5][5] = { {2,4,1,2,1},{3,4,2,3,3},{2,4,1,2,2},{4,4,4,1,2},{4,2,3,3,2} };
while (1)
{
garo = false, sero = false;
check_garo(board,garo);
Draw_Game(board);
check_sero(board,sero);
Draw_Game(board);
if (garo == false && sero == false)
break;
}
}
코드가 굉장히 더럽습니다. 여러분의 눈을 더럽혀 정말 죄송합니다...
def num():
array=[2, 4, 1, 2, 1,0], [3, 4, 2, 3, 3,0],[2, 4, 1, 2, 2,0],[4, 4, 4, 1, 2,0],[4, 2, 3, 3, 2,0],[0,0,0,0,0,0]
return array
def arr(array):
for i in range(0,5):
for j in range(0,5):
if array[i][j]==array[i][j-1] and array[i][j]==array[i][j+1] and array[i][j]!=0:
array[i][j]=0
array[i][j-1]=0
array[i][j+1]=0
if array[i][j]==array[i-1][j] and array[i][j]==array[i+1][j] and array[i][j]!=0:
array[i][j]=0
array[i-1][j]=0
array[i+1][j]=0
return array
def up(array):
for k in range(0,6):
for i in range(4,0,-1):
for j in range(4,-1,-1):
if array[i][j] == 0:
array[i][j] = array[i-1][j]
array[i-1][j] = 0
return array
def result(array):
arr(array)
up(array)
arr(array)
up(array)
arr(array)
up(array)
print(array[0])
print(array[1])
print(array[2])
print(array[3])
print(array[4])
//result(num())
import numpy as np
from itertools import groupby
m = np.zeros((5,5),dtype=int)
for i in range(5):
m[4-i] = list(map(int,input().split()))
def to_zero( l ):
for i in range(len(l)):
if len(l[i]) >= 3 and l[i][0] != '0':
l[i] = '0' * len(l[i])
return [int(x) for x in ''.join(l)]
def get_hstr_grouping( m, row_no ):
hs = ''.join(map(str,m[row_no]))
hl = [ ''.join(i) for _, i in groupby(hs) ]
return hl
def get_vstr_grouping( m, col_no ):
l = [ x[col_no] for x in m ]
vs = ''.join(map(str,l))
vl = [ ''.join(t) for _, t in groupby(vs) ]
return vl
def pung_horizontal( m ):
for rowid in range(5):
hl = get_hstr_grouping( m, rowid )
hl = to_zero(hl)
m[rowid] = hl
def pung_vertical( m ):
for col in range(5):
vl = get_vstr_grouping( m, col )
vl = to_zero(vl)
for i in range(len(vl)):
m[i,col] = vl[i]
def moveb( m, row, col ):
if row < m.shape[0]:
for i in range(row, m.shape[0]):
m[i-1,col] = m[i,col]
m[m.shape[0]-1,col] = 0
def shift_block( m ):
need_move = 0
moved = 0
for col in range(m.shape[1]):
for row in range(m.shape[0]):
while m[row,col] == 0:
for i in range(row+1,m.shape[0]):
if m[i,col] != 0:
need_move = 1
if need_move == 1:
moveb(m,row+1,col)
moved = 1
need_move = 0
else: break
return moved;
moved = 1
while moved != 0:
pung_horizontal(m)
pung_vertical(m)
moved = shift_block(m)
for i in range(5):
print( ' '.join( list(map(str,m[4-i])) ))
from collections import defaultdict
class anipeong:
def __init__(self,data):
self.__data = [i.split() for i in data.split('\n')]
self.__data = [*map(list,zip(*self.__data))]
self.__n = len(self.__data)
def __search(self):
schrow = self.__same3overtile(self.__data)
schclm = self.__same3overtile(zip(*self.__data))
for i,j in schclm.items():
for k in j: schrow[k].add(i)
return schrow
def __same3overtile(self,data):
ret = defaultdict(set)
for i,j in enumerate(data):
for k in range(self.__n-2):
if '0' not in j[k:k+3] and len(set(j[k:k+3])) == 1:
for x in (k,k+1,k+2): ret[i].add(x)
return ret
def __peong(self,coord):
for i,j in enumerate(self.__data):
for k in coord[i]: j[k] = ''
self.__data[i] = [k for k in ''.join(j).zfill(self.__n)]
def main(self):
while 1:
self.printdata()
peongcoord = self.__search()
if peongcoord: self.__peong(peongcoord)
else: break
def printdata(self):
for j in range(self.__n):
for i in range(self.__n):
print(self.__data[i][j],end=' ')
print()
print()
if __name__ == '__main__':
inp = '''\
2 4 1 2 1
3 4 2 3 3
2 4 1 2 2
4 4 4 1 2
4 2 3 3 2'''
x = anipeong(inp)
x.main()
뭔가 예쁘게 잘 안 되네요.
# 가로 또는 세로 한 줄을 입력 받아 터뜨릴 자리를 True, 아니면 False로 리턴
def line_marker(tiles):
t, r, sl = tiles + ['0'], [], [] # tile, result_list, sublist
for i in range(len(t)):
if i < len(t) - 1 and (not sl or t[i] is sl[0]):
sl.append(t[i])
else:
r += [False if (len(sl) < 3 or sl[0] is '0') else True for t in sl]
sl = [t[i]]
return r
def pung(board, size):
# 터뜨릴 자리를 마킹
marker = [[False for col in row] for row in board]
for i in range(size):
row_marker = line_marker(board[i])
col_marker = line_marker([row[i] for row in board])
for j in range(size):
marker[i][j] = marker[i][j] or row_marker[j]
marker[j][i] = marker[j][i] or col_marker[j]
# marker를 board에 적용
changed = False
for i in range(size):
for j in range(size):
if marker[i][j]:
board[i][j] = '0'
changed = True
return changed
# 빈 칸 채우기
def collapse(board, size):
for i in range(size - 2, -1, -1):
for j in range(size):
if board[i][j] is not '0':
k = i
while (k + 1 < size and board[k + 1][j] is '0'):
board[k][j], board[k + 1][j] = '0', board[k][j]
k += 1
rawdata = \
'''2 4 1 2 1
3 4 2 3 3
2 4 1 2 2
4 4 4 1 2
4 2 3 3 2'''
board = [line.split() for line in rawdata.split('\n')]
size = len(board)
while (pung(board, size)):
collapse(board, size)
for row in board:
print(' '.join(row))
class Check{
int[][] board = new int[5][5], boarddummy = new int[5][5];
int flag=0;
public Check(int[][] board) {
this.board = board;
this.boarddummy = board;
}
public void checkchain() {
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++){
if(board[i][j] != 0){
if(j < 3)
if(board[i][j] == board[i][j+1] && board[i][j] == board[i][j+2]){
boarddummy[i][j] = 0;
boarddummy[i][j+1] = 0;
boarddummy[i][j+2] = 0;
flag = 1;
}
if(i < 3)
if(board[i][j] == board[i+1][j] && board[i][j] == board[i+2][j]){
boarddummy[i][j] = 0;
boarddummy[i+1][j] = 0;
boarddummy[i+2][j] = 0;
flag = 1;
}
}
}
if(flag == 1){
for(int j = 0; j < 5; j++)
for(int i = 0; i < 5; i++){
if(boarddummy[i][j] == 0){
for(int k = i; k > 0; k--){
boarddummy[k][j] = boarddummy[k-1][j];
boarddummy[k-1][j] = 0;
}
}
}
flag = 0;
board = boarddummy;
checkchain();
}
else
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++)
System.out.print("<" + board[i][j] + ">");
System.out.println("\n");
}
}
}
public class Three {
public static void main(String[] args){
int[][] board = {{2,4,1,2,1},{3,4,2,3,3},{2,4,1,2,2},{4,4,4,1,2},{4,2,3,3,2}};
Check check = new Check(board);
check.checkchain();
}
}
pung = [[2, 4, 1, 2, 1],[3, 4, 2, 3, 3],[2, 4, 1, 2, 2],[4, 4, 4, 1, 2],[4, 2, 3, 3, 2]]
evalu = [[False for i in range(0,5)] for i in range(0,5)]
seq = 1
counter = True
while any([any(arr) for arr in evalu])+counter:
evalu = [[False for i in range(0,5)] for i in range(0,5)]
for i in range(0,5):
for j in range(0,5):
if pung[i][j] != 0:
for k in range(j-1,-1,-1):
if pung[i][j] == pung[i][k]:
seq += 1
else:
break
for k in range(j+1,5):
if pung[i][j] == pung[i][k]:
seq += 1
else:
break
for k in range(i-1,-1,-1):
if pung[i][j] == pung[k][j]:
seq += 1
else:
break
for k in range(i+1,5):
if pung[i][j] == pung[k][j]:
seq += 1
else:
break
if seq >= 3:
evalu[i][j] = True
seq = 1
counter = False
for i in range(0,5):
for j in range(0,5):
if evalu[i][j] == True:
pung[i][j] = 0
for j in range(0,5):
for i in range(4,-1,-1):
while pung[i][j] == 0:
for k in range(i,0,-1):
pung[k][j] = pung[k-1][j]
pung[0][j] = 0
if sum([pung[l][j] for l in range(0,i)]) == 0:
break
for i in range(0,5):
print(pung[i])
# 타일판은 5 × 5
# 타일 종류는 1 ~ 4의 네 지가
# 가로나 세로로 3개 이상 같은 타일이 연속될 경우 펑! 사라지고, 그 자리에는 위쪽의 타일들이 내려와서 메꿉니다.
# 내려오면서 비게 된 자리는 0으로 채워집니다.
# 위의 규칙대로 동작하는 프로그램을 작성해주세요.
#
# 프로그래밍 언어에 제약은 없지만, 외부 라이브러리는 사용하지 마세요.
#매트릭스 만들기(랜덤으로 했어요)
import random
matrix= [[random.randrange(1,5) for i in range(5)] for i in range(5)]
print('시작!')
# 현재 현황 확인
def chk():
print('-------------------')
for i in range(5):
for j in range(5):
print("{0:<4}".format(matrix[i][j]), end='')
print('')
chk()
def cont(n):
save_num_row = 0
save_num_col = 0
count_row = 1
count_col = 1
for j in range(4):
#Row 연속 3개 이상 수 찾기
if matrix[n][j] == matrix[n][j+1]: #오른쪽 수와 같은지?
count_row += 1
if matrix[n][j] != matrix[n][j+1]: #다르다면 초기화
count_row = 1
if count_row >= 3: #3개 이상 Count된다면
save_num_row = matrix[n][j]
#Column 연속 3개 이상 수 찾기
if matrix[j+1][n] == matrix[j][n]: #아래쪽 수와 같은지?
count_col += 1
if matrix[j+1][n] != matrix[j][n]: #다르다면 초기화
count_col = 1
if count_col >= 3: #3개 이상 Count된다면
save_num_col = matrix[j][n]
#값을 저장하여 return
return [save_num_row,save_num_col]
while True:
stop = 0
complete = 0
delete = []
#3개 이상의 수 찾아서 삭제 기록 리스트에 넣기
for i in range(5):
delete.append(cont(i))
print('\n+ 한바퀴')
#팡!
for i in range(5):
for j in range(5):
# 좌우 확인
if j == 0 and matrix[i][j] != matrix[i][j + 1] and matrix[i][j] == delete[i][0]: # 같은수이지만 떨어져있는경우(0되는 것 방지)
continue
if j == 4 and 0 == matrix[i][j - 1] and matrix[i][j] == delete[i][0]: # 0이 되어야 하는데 안되는것 방지
matrix[i][j] = 0
continue
# 상하 확인
if i == 0 and matrix[i][j] != matrix[i + 1][j] and matrix[i][j] == delete[j][1]: # 같은수이지만 떨어져있는경우(0되는 것 방지)
continue
if i == 4 and 0 == matrix[i - 1][j] and matrix[i][j] == delete[j][1]: # 0이 되어야 하는데 안되는것 방지
matrix[i][j] = 0
continue
# 0 채우기
if matrix[i][j] == delete[i][0]:
matrix[i][j] = 0
if matrix[i][j] == delete[j][1]:
matrix[i][j] = 0
chk()
#위로 올리기
while True:
zero_stop = 0
for i in range(4): #위로 한단계씩 올리기
for j in range(5):
if matrix[i+1][j] == 0:
matrix[i+1][j] = matrix[i][j]
matrix[i][j] = 0
for i in range(4): #만약 자신이 0이 아닌데 아래에 0이 있다면 한바퀴 더
for j in range(5):
if matrix[i][j] !=0 and matrix[i+1][j] == 0:
zero_stop += 1
if zero_stop == 0:
break
chk()
#delete에 리스트가 비었다면 더 이상 없앨 수가 없어 종료
for i in range(5):
for j in range(2):
if delete[i][j] != 0:
complete += 1
if complete == 0:
print('최종')
break
5시간을 했네요.. 왜 돌아가는지 몰라요..
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int map1[5][5]={0,};
int map2[5][5]={0,};
int i,j,c,count,k;
srand(time(NULL));
//랜덤 생성
printf("\nmap1 first\n") ;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
map1[i][j]=rand()%4+1;
printf("%d",map1[i][j]);
}
printf("\n");
}
while(1)
{
count=0;
//checker-column
for(i=0;i<5;i++)
{
for(j=0;j<3;j++)
{
if(map1[i][j]==map1[i][j+1]&&map1[i][j+1]==map1[i][j+2]&&map1[i][j]!=0)
{
map2[i][j]=1;
map2[i][j+1]=1;
map2[i][j+2]=1;
}
}
}
//checker-row
for(j=0;j<5;j++)
{
for(i=0;i<3;i++)
{
if(map1[i][j]==map1[i+1][j]&&map1[i+1][j]==map1[i+2][j]&&map1[i][j]!=0)
{
map2[i][j]=1;
map2[i+1][j]=1;
map2[i+2][j]=1;
}
}
}
//remover
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(map2[i][j]==1)
{
map1[i][j]=0;
map2[i][j]=0;
count=count+1;
}
}
}
printf("%d\n",count);
//gravity
for(c=0;c<=10;c++)
{
for(j=0;j<5;j++)
{
for(i=0;i<4;i++)
{
if(map1[i+1][j]==0)
{
map1[i+1][j]=map1[i][j];
map1[i][j]=0;
}
}
}
}
if(count==0)
break;
}
//map1 end
printf("\nmap1 last\n");
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("%d",map1[i][j]);
}
printf("\n");
}
getch();
return 0;
}
def enifungGame(tile):
for r in range(5):
for c in range(5):
if c < 3 and tile[r][c] % 10 == tile[r][c+1] % 10 == tile[r][c+2]%10:
value = tile[r][c] % 10
k = c
while k<5 and tile[r][k]%10 == value:
tile[r][k] = 10 + value
k += 1
if r < 3 and tile[r][c]%10 == tile[r+1][c]%10 == tile[r+2][c]%10:
value = tile[r][c] % 10
k = r
while k < 5 and tile[k][c] % 10 == value:
tile[k][c] = 10 + value
k += 1
moveTile(tile)
print()
printTile(tile)
def moveTile(tile):
for r in range(4,-1,-1):
for c in range(5):
if tile[r][c] > 10 or tile[r][c] == 0:
tile[r][c] = 0
k = r-1
while k >= 0:
if 0 <tile[k][c] < 10:
tile[r][c], tile[k][c] = tile[k][c], 0
break
else:
k -= 1
return tile
def printTile(tile):
for r in range(5):
for c in range(5):
print('{0:3}'.format(tile[r][c]), end=' ')
print()
tile = [[2, 4, 1, 2, 1], [3, 4, 2, 3, 3], [2, 4, 1, 2, 2],
[4, 4, 4, 1, 2], [4, 2, 3, 3, 2]]
printTile(tile)
enifungGame(tile)