Thứ Hai, 5 tháng 9, 2016

[writeup][TWCTF][ppc50] Make a Palindrome!


Đề đại khái là nó cho 1 chuỗi gồm các str ngăn bởi space. Giờ phải sắp xếp sao cho  chuỗi đó thành chuỗi palindrome ( có nghĩa là xuôi ngược đều như nhau ) mà vẫn giữ nguyên dấu cách. 
Time limit 3m
Có 30 test cases. Flag sẽ nằm ở case 1 và case 30.
Hiểu đề rồi thì code thôi.
Đề file 7z của nó gồm có 2 cái example của python và perl. Mình code python nên sẽ up python 
# -*- coding:utf-8 -*-
# Server connection example file for Python 2
import socket
import sys

host = 'ppc1.chal.ctf.westerns.tokyo'
if len(sys.argv) > 1:
    host = sys.argv[1]
port = 31111
if len(sys.argv) > 2:
    host = int(sys.argv[2])

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))

client_file = client.makefile('b')

while client_file.readline().strip() != "Let's play!":
    pass

client_file.readline()
for case in range(0, 30):
    client_file.readline()
    words = client_file.readline().split()[2:]
    # words: input
    # answer: answer
    ##  Please write some code here
    answer = words
    #
    client_file.write(' '.join(answer) + "\n")
    client_file.flush()
    ret = client_file.readline()[8:-1]
    print(ret)
    if 'Wrong Answer' in ret:
        print(client_file.readline())
        sys.exit(1)



Thuật toán của mình cũng khá đơn giản.  Mình sẽ dùng permutations để tạo ra các hoán vị từ dữ liệu đã cho. Sau đó kiểm tra bằng hàm ispalindrome. Hàm này chỉ đảo ngược chuỗi lại và so sánh với chuỗi ban đầu . Code :

# -*- coding:utf-8 -*-
# Server connection example file for Python 2
import socket
import sys
import itertools
def ispalindrome(word):
    return word == word[::-1]
def palindrome(w):
    for x in list(itertools.permutations(w,len(w))):
        t=''.join(x)
        if ispalindrome(t):
            return x 
host = 'ppc1.chal.ctf.westerns.tokyo'
if len(sys.argv) > 1:
    host = sys.argv[1]
port = 31111
if len(sys.argv) > 2:
    host = int(sys.argv[2])

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host, port))

client_file = client.makefile('b')

while client_file.readline().strip() != "Let's play!":
    pass

client_file.readline()
for case in range(0, 30):
    client_file.readline()
    words = client_file.readline().split()[2:]
    # words: input
    # answer: answer
    ##  Please write some code here
    answer = palindrome(words)
    #
    client_file.write(' '.join(answer) + "\n")
    client_file.flush()
    ret = client_file.readline()[8:-1]
    print(ret)
    if 'Wrong Answer' in ret:
        print(client_file.readline())
        sys.exit(1)
Run : 

Không có nhận xét nào:

Đăng nhận xét