このcountRunsなんですけど、
やらなくてはいけないことは基本的に
coins [] に入ってる要素、例えば
"HTHHTT"だったとすると
"H", "T", "HH", "TT" で4と数えなければならないのですが、
どうにも数え方が思いつきません。
どなたか手を貸していただけないでしょうか?
コード package week02; /** Coin tossess. @author Tomofumi Kimura */ import java.util.Random; import java.util.Iterator; public class Coins{ /** Coins tosses. */ public static final boolean HEADS = true; public static final boolean TAILS = false; private boolean[] coins; public static void main(String [] args){ /** @param none */ //boolean [] b = {HEADS, TAILS,HEADS, HEADS, TAILS}; //Coins c = new Coins(b); //System.out.println(c.countHeads()); //System.out.println(c.toString()); //String result = c.toString(); //Coins c2 = new Coins("HHHH"); //System.out.println(c2.countHeads()); //Coins c3 = new Coins(10); //System.out.println(c3.toString()); Coins c4 = new Coins("HHTTHT"); System.out.println(c4.countRuns()); } public Coins(boolean[] coins){ this.coins = coins; } public Coins(String c){ /** read String consisting H and T and make boolean coins 1. read H and T and put HEADS and TAILS into coins array */ this.coins = new boolean [c.length()]; for (int i=0;i<c.length();i++){ if (c.charAt(i)=='H'){ this.coins[i] = HEADS; }else if (c.charAt(i)== 'T'){ this.coins[i] = TAILS; } } } public Coins(int length){ this.coins = new boolean[length]; Random rand = new Random(); for (int i = 0; i<length;i++){ int value = rand.nextInt(10); if (value%2 == 0){ this.coins[i] = HEADS; }else{ this.coins[i] = TAILS; } } } public int countHeads(){ /** @param none @return the number of occurrences of heads */ int count=0; for (boolean s:this.coins){ if(s== true){ count++; } } return count; } public int countRuns(){ /** @param none @return the number of runs in this sequence of coins */ int size = 0; int count =0; for (boolean t: this.coins){ size++; } return size; // HH TT H T } public String toString(){ /** @param none @return String */ String result = ""; for (boolean s:this.coins){ if (s== true){ result+= "H"; }else{ result+= "T"; } } return result; } }
このcountRunsなんですけど、
やらなくてはいけないことは基本的に
coins [] に入ってる要素、例えば
"HTHHTT"だったとすると
"H", "T", "HH", "TT" で4と数えなければならないのですが、
どうにも数え方が思いつきません。
どなたか手を貸していただけないでしょうか?
回答4件
あなたの回答
tips
プレビュー