分布與并行計算—生命游戲(Java)

生命游戲其實是一個零玩家游戲,它包括一個二維矩形世界,這個世界中的每個方格居住著一個活著的或死了的細胞。一個細胞在下一個時刻生死取決于相鄰八個方格中活著的或死了的細胞的數量。如果相鄰方格活著的細胞數量過多,這個細胞會因為資源匱乏而在下一個時刻死去;相反,如果周圍活細胞過少,這個細胞會因太孤單而死去。
具體規則如下:

1)如果一個細胞周圍有3個細胞為生(一個細胞周圍共有8個細胞),則該細胞為生(即該細胞若原先為死,則轉為生,若原先為生,則保持不變) 。
2) 如果一個細胞周圍有2個細胞為生,則該細胞的生死狀態保持不變;
3) 在其它情況下,該細胞為死(即該細胞若原先為生,則轉為死,若原先為死,則保持不變)
在程序中,使用0代表死,1代表生。

串行模式

public class lifegame {public static List<String> readTxt(String fileName){List<String> list=new ArrayList<>();try { // 防止文件建立或讀取失敗,用catch捕捉錯誤并打印,也可以throw/* 讀入TXT文件 */File filename = new File(fileName); // 要讀取以上路徑的input。txt文件InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一個輸入流對象readerBufferedReader br = new BufferedReader(reader); // 建立一個對象,它把文件內容轉成計算機能讀懂的語言String line = "";line = br.readLine();while (line != null) {list.add(line);line = br.readLine();}} catch (Exception e) {e.printStackTrace();}return list;}public static void writeTxt(String content){try { // 防止文件建立或讀取失敗,用catch捕捉錯誤并打印,也可以throw/* 讀入TXT文件 */File writename = new File("output.txt"); // 相對路徑,如果沒有則要建立一個新的output。txt文件writename.createNewFile(); // 創建新文件BufferedWriter out = new BufferedWriter(new FileWriter(writename));out.write(content); // \r\n即為換行out.flush(); // 把緩存區內容壓入文件out.close(); // 最后記得關閉文件} catch (Exception e) {e.printStackTrace();}}public boolean[][] world;public int len;int times;public lifegame(List<String> list) {int n=Integer.parseInt(list.get(0));world=new boolean[n][n];this.len=n;this.times=Integer.parseInt(list.get(1));System.out.println(len);for(int i=2;i<list.size();i++){String[] temp=list.get(i).split(",");int x=Integer.parseInt(temp[0]),y=Integer.parseInt(temp[1]);world[x][y]=true;}System.out.println(list.get(0)+times);}public  void print(){for(int i=0;i<len;i++){for(int j=0;j<len;j++)if(world[i][j])System.out.print(1);else System.out.print(0);System.out.println();}System.out.println();}private int[][] dir=new int[][]{{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,-1},{-1,1},{1,-1}};public  void change(){int[][] count=new int[len][len];for(int i=0;i<len;i++)for(int j=0;j<len;j++)count[i][j]=count(i,j);for(int i=0;i<len;i++)for(int j=0;j<len;j++)if(count[i][j]==3){world[i][j]=true;}else if(count[i][j]!=2)world[i][j]=false;}public  int count(int x,int y){int ret=0;for(int[] c:dir){int nextX=c[0]+x,nextY=c[1]+y;if(nextX>=0&&nextX<len&&nextY>=0&&nextY<len){ret+=world[nextX][nextY]?1:0;}}return ret;}public static void main(String[] args){lifegame on=new lifegame(readTxt("input.txt"));for(int i=0;i<on.times;i++){on.change();}StringBuilder stringBuilder=new StringBuilder();for(int i=0;i<on.len;i++)for(int j=0;j<on.len;j++){if(on.world[i][j]){stringBuilder.append(i).append(',').append(j).append("\r\n");}}writeTxt(stringBuilder.toString());}
}

并行模式

public class lifegame2 {public static List<String> readTxt(String fileName){List<String> list=new ArrayList<>();try { // 防止文件建立或讀取失敗,用catch捕捉錯誤并打印,也可以throw/* 讀入TXT文件 */File filename = new File(fileName); // 要讀取以上路徑的input。txt文件InputStreamReader reader = new InputStreamReader(new FileInputStream(filename)); // 建立一個輸入流對象readerBufferedReader br = new BufferedReader(reader); // 建立一個對象,它把文件內容轉成計算機能讀懂的語言String line = "";line = br.readLine();while (line != null) {list.add(line);line = br.readLine();}} catch (Exception e) {e.printStackTrace();}return list;}public static void writeTxt(String content){try { // 防止文件建立或讀取失敗,用catch捕捉錯誤并打印,也可以throw/* 讀入TXT文件 */File writename = new File("output.txt"); // 相對路徑,如果沒有則要建立一個新的output。txt文件writename.createNewFile(); // 創建新文件BufferedWriter out = new BufferedWriter(new FileWriter(writename));out.write(content); // \r\n即為換行out.flush(); // 把緩存區內容壓入文件out.close(); // 最后記得關閉文件} catch (Exception e) {e.printStackTrace();}}int[][] count;private boolean[][] world;int len;public int times;public int getTimes() {return times;}public lifegame2(List<String> list) {int n=Integer.parseInt(list.get(0));world=new boolean[n][n];count=new int[n][n];this.len=n;this.times=Integer.parseInt(list.get(1));System.out.println(len);for(int i=2;i<list.size();i++){String[] temp=list.get(i).split(",");int x=Integer.parseInt(temp[0]),y=Integer.parseInt(temp[1]);world[x][y]=true;}System.out.println(list.get(0)+times);}public  void print(){for(int i=0;i<len;i++){for(int j=0;j<len;j++)if(world[i][j])System.out.print(1);else System.out.print(0);System.out.println();}System.out.println();}public  String excute(int c){ExecutorService executorService= Executors.newFixedThreadPool(c);for(int j=0;j<times;j++){CountDownLatch countDownLatch=new CountDownLatch(c);Thread[] threads = new Thread[10];for(int i=0;i<len;i+=len/c){excuteThread cur=new excuteThread(count,i,i+len/c-1,world,countDownLatch);executorService.execute(cur);}try {countDownLatch.await();} catch (InterruptedException e) {e.printStackTrace();}for(int i=0;i<len;i++)for(int k=0;k<len;k++)if(count[i][k]==3){world[i][k]=true;}else if(count[i][k]!=2)world[i][k]=false;System.out.printf("第%d輪結束\n",j);}executorService.shutdown();while (!executorService.isTerminated()){}StringBuilder stringBuilder=new StringBuilder();for(int i=0;i<len;i++)for(int j=0;j<len;j++){if(world[i][j]){stringBuilder.append(i).append(',').append(j).append("\r\n");}}return stringBuilder.toString();}public static void main(String[] args){lifegame2 on=new lifegame2(readTxt("input.txt"));long s=System.currentTimeMillis();String t=on.excute(4);System.out.println(((double) (System.currentTimeMillis()-s))/1000);writeTxt(t);}
}
public class excuteThread implements  Runnable{int[][] count;int l,r,len;boolean[][] world;CountDownLatch countDownLatch;public excuteThread(int [][] count,int l,int r,boolean[][] world,CountDownLatch countDownLatch) {len=count.length;this.count=count;this.l=l;this.r=r;this.countDownLatch=countDownLatch;this.world=world;}@Overridepublic void run() {System.out.println("線程"+l*4/len+"開始");for(int i=0;i<len;i++)for(int j=l;j<=r;j++)count[i][j]=count(i,j);System.out.println("線程"+l*4/len+"結束");countDownLatch.countDown();}private int[][] dir=new int[][]{{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,-1},{-1,1},{1,-1}};public  int count(int x,int y){int ret=0;for(int[] c:dir){int nextX=c[0]+x,nextY=c[1]+y;if(nextX>=0&&nextX<len&&nextY>=0&&nextY<len){ret+=world[nextX][nextY]?1:0;}}return ret;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/392198.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392198.shtml
英文地址,請注明出處:http://en.pswp.cn/news/392198.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

正確認識 Vista 激活期限

當我們在安裝 Vista 時&#xff0c;可以不輸入序列號進行安裝&#xff0c;這和以往的操作系統安裝有所不同&#xff0c;我們不必再為安裝系統時找不到我們的序列號標簽而發愁。如果不輸入序列號而繼續安裝系統&#xff0c;那么系統將提示我們有30天的激活期限&#xff01;這里的…

Oracle使用hs odbc連接mssql2008

1.創建odbc 2.在 product\11.2.0\dbhome_1\hs\admin\ 下拷貝initdg4odbc,把名字改為initcrmsql&#xff08;init所建odbc的名稱&#xff09; HS_FDS_CONNECT_INFO crmsql #odbc名稱 HS_FDS_TRACE_LEVEL 0 HS_FDS_RECOVERY_ACCOUNTsa #要連接的數據庫名稱 HS_FDS_RECOVERY_PWD…

oracle修改物化視圖字段,獲取物化視圖字段的修改矢量(一)

當表建立了物化視圖日志之后&#xff0c;表的DML修改會被記錄到物化視圖日志中&#xff0c;而物化視圖日志則包含了一個修改矢量&#xff0c;來記錄哪個列被修改。在文章列的修改矢量可以通過2的N次方來獲得&#xff0c;也就是POWER(2, N)。而N的值&#xff0c;就是列的位置。但…

聚合 數據處理_R中聚合的簡介:強大的數據處理工具

聚合 數據處理by Satyam Singh Chauhan薩蒂揚辛格喬漢(Satyam Singh Chauhan) R中聚合的簡介&#xff1a;強大的數據處理工具 (An introduction to aggregates in R: a powerful tool for playing with data) Data Visualization is not just about colors and graphs. It’s …

大數據 notebook_Dockerless Notebook:數據科學期待已久的未來

大數據 notebookData science is hard. Data scientists spend hours figuring out how to install that Python package on their laptops. Data scientists read many pages of Google search results to connect to that database. Data scientists write a detailed docume…

【NGN學習筆記】6 代理(Proxy)和背靠背用戶代理(B2BUA)

1. 什么是Proxy模式&#xff1f; 按照RFC3261中的定義&#xff0c;Proxy服務器是一個中間的實體&#xff0c;它本身即作為客戶端也作為服務端&#xff0c;為其他客戶端提供請求的轉發服務。一個Proxy服務器首先提供的是路由服務&#xff0c;也就是說保證請求被發到更加”靠近”…

分布與并行計算—并行計算π(Java)

并行計算π public class pithread extends Thread {private static long mini1000000000;private long start,diff;double sum0;double cur1/(double)mini;public pithread(long start,long diff) {this.startstart;this.diffdiff;}Overridepublic void run() {long istart;f…

linux復制文件跳過相同,Linux cp指令,怎么跳過相同的文件

1、使用cp命令的-n參數即可跳過相同的文件 。2、cp命令使用詳解&#xff1a;1)、用法&#xff1a;cp [選項]... [-T] 源文件 目標文件或&#xff1a;cp [選項]... 源文件... 目錄或&#xff1a;cp [選項]... -t 目錄 源文件...將源文件復制至目標文件&#xff0c;或將多個源文件…

eclipse類自動生成注釋

1.創建新類時自動生成注釋 window&#xff0d;>preference&#xff0d;>java&#xff0d;>code styple&#xff0d;>code template 當你選擇到這部的時候就會看見右側有一個框顯示出code這個選項&#xff0c;你點開這個選項&#xff0c;點一下他下面的New …

rman恢復

--建表create table sales( product_id number(10), sales_date date, sales_cost number(10,2), status varchar2(20));--插數據insert into sales values (1,sysdate-90,18.23,inactive);commit; --啟用rman做全庫備份 運行D:\autobackup\rman\backup_orcl.bat 生成…

微軟大數據_我對Microsoft的數據科學采訪

微軟大數據Microsoft was one of the software companies that come to hire interns at my university for 2021 summers. This year, it was the first time that Microsoft offered any Data Science Internship for pre-final year undergraduate students.微軟是到2021年夏…

再次檢查打印機名稱 并確保_我們的公司名稱糟透了。 這是確保您沒有的方法。...

再次檢查打印機名稱 并確保by Dawid Cedrych通過戴維德塞德里奇 我們的公司名稱糟透了。 這是確保您沒有的方法。 (Our company name sucked. Here’s how to make sure yours doesn’t.) It is harder than one might think to find a good business name. Paul Graham of Y …

linux中文本查找命令,Linux常用的文本查找命令 find

一、常用的文本查找命令grep、egrep命令grep&#xff1a;文本搜索工具&#xff0c;根據用戶指定的文本模式對目標文件進行逐行搜索&#xff0c;先是能夠被模式匹配到的行。后面跟正則表達式&#xff0c;讓grep工具相當強大。-E之后還支持擴展的正則表達式。# grep [options] …

分布與并行計算—日志挖掘(Java)

日志挖掘——處理數據、計費統計 1、讀取附件中日志的內容&#xff0c;找出自己學號停車場中對應的進出車次數&#xff08;in/out配對的記錄數&#xff0c;1條in、1條out&#xff0c;視為一個車次&#xff0c;本日志中in/out為一一對應&#xff0c;不存在缺失某條進或出記錄&a…

《人人都該買保險》讀書筆記

內容目錄&#xff1a; 1.你必須知道的保險知識 2.家庭理財的必需品 3.保障型保險產品 4.儲蓄型保險產品 5.投資型保險產品 6.明明白白買保險 現在我所在的公司Manulife是一家金融保險公司&#xff0c;主打業務就是保險&#xff0c;因此我需要熟悉一下保險的基礎知識&#xff0c…

Linux下查看txt文檔

當我們在使用Window操作系統的時候&#xff0c;可能使用最多的文本格式就是txt了&#xff0c;可是當我們將Window平臺下的txt文本文檔復制到Linux平臺下查看時&#xff0c;發現原來的中文所有變成了亂碼。沒錯&#xff0c; 引起這個結果的原因就是兩個平臺下&#xff0c;編輯器…

如何擊敗騰訊_擊敗股市

如何擊敗騰訊個人項目 (Personal Proyects) Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an…

滑塊 組件_組件制作:如何使用鏈接的輸入創建滑塊

滑塊 組件by Robin Sandborg羅賓桑德伯格(Robin Sandborg) 組件制作&#xff1a;如何使用鏈接的輸入創建滑塊 (Component crafting: how to create a slider with a linked input) Here at Stacc, we’re huge fans of React and the render-props pattern. When it came time…

配置靜態IPV6 NAT-PT

一.概述&#xff1a; IPV6 NAT-PT( Network Address Translation - Port Translation)應用與ipv4和ipv6網絡互訪的情況&#xff0c;根據參考鏈接配置時出現一些問題&#xff0c;所以記錄下來。參考鏈接&#xff1a;http://www.cisco.com/en/US/tech/tk648/tk361/technologies_c…

linux 線程與進程 pid,linux下線程所屬進程號問題

這一段看《unix環境高級編程》&#xff0c;一個關于線程的小例子。#include#include#includepthread_t ntid;void printids(const char *s){pid_t pid;pthread_t tid;pidgetpid();tidpthread_self();printf("%s pid %u tid %u (0x%x)n",s,(unsigned int)pid,(unsigne…