java&python-APCS-2023/1/8實作第二題:造字程式 === ### ZeroJudge:j606造字程式 ### <font color="#FFCC22">(for新手)簡單題分析</font> #### (java在最後面,概念是一樣的,可以搭配著看) --- \ \ \ \ \ <font color="#FFEE99">**1初始設置**</font> --- k代表初始字串Word的長度 q代表重新排列的次數 r代表輸出重新排列字串的次數 sortedWords用來存放q個已經重新排列好的字串 ```python= k, q, r = map(int, input().split()) Word = input() sortedWords = [] ``` \ \ \ <font color="#FFEE99">**2存放每一回合的新字串**</font> --- (操作前置作業) 接下來總共還有q筆排列的順序,用sortWay來存放 初始化字串tempWord用來存放Word經由sortWay來排序的字串 :::info (操作) 範例: 字串: a c b c a index:0,1,2,3,4 data: 3,4,2,1,0 (這個是sortWay存放的資料) 運作方法:index為0的a要放到index為3的位置..以此類推 tempWord = acbac \ ->我的作法: 在data中找出0 -> 將這筆資料轉成字串索引值 -> 索引位置的資料是a 加入tempWord tempWord = a 在data中找出1 -> 將這筆資料轉成字串索引值 -> 索引位置的資料是c 加入tempWord tempWord = ac ..以此類推 ::: \ (回到程式碼)line6 sortWay.index(i)是不斷找出data中的1,2,3,4,5... 然後Word[SortWay.index(i)]是找出索引位置的資料,加入tempWord 註:因為索引值是從0開始的,所以range是從1到k+1 \ (最後) 把排好的tempWord加入sortedWords中存放 並且讓下一個word變成tempWord ```python= # 操作前置作業 for _ in range(q): tempWord = "" sortWay = [int(i)for i in input().split()] #操作 for i in range(1, k+1): tempWord += Word[sortWay.index(i)] sortedWords.append(tempWord) Word = tempWord ``` \ \ \ <font color="#FFEE99">**3取出新單字**</font> --- :::info (取出單字的方法) 範例: 以下三個是各階段排好的資料(存放在sortedWords中) bcaa bcaa abca 取出資料->直的一列取出r個單字(假設r = 3) bba ccb aac ->我的作法: 如果r是3,就取出串列中所有索引值=0的字元,取出串列中所有索引值=1的字元,取出串列中所有索引值=2的字元 ::: 回到程式碼 popWordsIndex存放目前要取出的字元索引值 wordsInList一一取出串列中的字串 line3一一輸出字元,end=""同一個字串放入的字元不換行 line4輸出完一個字串之後換行 ```python= for popWordsIndex in range(r): for wordsInList in sortedWords: print(wordsInList[popWordsIndex], end="") print() ``` \ \ \ <font color="#FFEE99">**完整程式碼**</font> --- ```python= k, q, r = map(int, input().split()) Word = input() sortedWords = [] for _ in range(q): tempWord = "" sortWay = [int(i)for i in input().split()] for i in range(1, k+1): tempWord += Word[sortWay.index(i)] sortedWords.append(tempWord) Word = tempWord for popWordsIndex in range(r): for wordsInList in sortedWords: print(wordsInList[popWordsIndex], end="") print() ``` <font color="#FFEE99">**JAVA完整程式碼**</font> --- ```java= package for_test; import java.util.*; public class apcs2023_01_2 { public static void main(String[] argv) { Scanner sc = new Scanner(System.in); int k = sc.nextInt(), q = sc.nextInt(), r = sc.nextInt(); String word = sc.next(); ArrayList<String> sortedWords = new ArrayList<>(); ArrayList<Integer> sortWay = new ArrayList<>(); for (int i = 0; i < q; i++) { sortWay.clear(); String tempWord = new String(""); for (int j = 0; j < k; j++) { sortWay.add(sc.nextInt()); } for (int j = 1; j <= k; j++) { tempWord += word.charAt(sortWay.indexOf(j)); } sortedWords.add(tempWord); word = tempWord; } sc.close(); for (int popWordsIndex = 0; popWordsIndex < r; popWordsIndex++) { for (String wordsInList : sortedWords) { System.out.print(wordsInList.charAt(popWordsIndex)); } System.out.println(); } } } ``` ###### tags: `題解` ###### tags: `APCS` ###### tags: `python` ###### tags: `java`