前提・実現したいこと
C#で実行回数を出力したいが、上手く実行できずに困っています。
下の様に複数回に分けて表示するのではなく、一括で表示させたいです。
発生している問題・エラーメッセージ
pushの実行回数は0回です. pushの実行回数は0回です. pushの実行回数は0回です. pushの実行回数は1回です. pushの実行回数は2回です. pushの実行回数は3回です. pushの実行回数は3回です. pushの実行回数は3回です. pushの実行回数は4回です. pushの実行回数は4回です. popの実行回数は2回です. popの実行回数は4回です. popの実行回数は5回です. popの実行回数は7回です. popの実行回数は9回です. popの実行回数は10回です. popの実行回数は11回です. popの実行回数は11回です. popの実行回数は11回です. popの実行回数は11回です. 実行時間は0.02792秒です.
該当のソースコード
C#
1using System; 2using System.Collections.Generic; 3using System.Linq; 4using System.Text; 5using System.Threading.Tasks; 6 7public class hoge { 8 9 public static void Main () { 10 Random rand = new Random (); 11 int[] data = new int[10]; 12 int n = data.Length; 13 14 // ランダムな数列を生成 15 for (int i = 0; i < n; i++) { 16 data[i] = rand.Next (1, 10); 17 } 18 //print (data); 19 20 DateTime startDt = DateTime.Now; 21 22 HeapArray heap = new HeapArray (n); 23 for (int i = 0; i < n; i++) heap.push (data[i]); 24 for (int i = 0; i < n; i++) data[i] = heap.pop (); 25 26 DateTime endDt = DateTime.Now; 27 TimeSpan ts = endDt - startDt; // 時間の差分を取得 28 System.Console.WriteLine ("実行時間は{0}秒です.", ts.TotalSeconds); // 経過時間(秒) 29 // System.Console.WriteLine (push_count); 30 // System.Console.WriteLine (pop_count); 31 //print (data); 32 } 33 34 public static void print (int[] ar) { 35 for (int i = 0; i < ar.Length; i++) System.Console.Write (ar[i] + " "); 36 System.Console.WriteLine (); 37 } 38} 39 40class HeapArray { 41 private int[] heap; 42 private int n; 43 44 public HeapArray (int size) { 45 heap = new int[size]; 46 n = 0; 47 } 48 private static int push_count = 0; 49 public void push (int x) { 50 51 heap[n] = x; 52 int child = n; 53 int parent = (n - 1) / 2; 54 while (child != 0 && x < heap[parent]) { 55 push_count++; 56 heap[child] = heap[parent]; 57 child = parent; 58 parent = (child - 1) / 2; 59 // System.Console.WriteLine ("pushの実行回数は{0}回です.", push_count); 60 } 61 System.Console.WriteLine ("pushの実行回数は{0}回です.", push_count); 62 heap[child] = x; 63 n++; 64 } 65 private static int pop_count = 0; 66 public int pop () { 67 68 int minValue = heap[0]; 69 heap[0] = heap[n - 1]; 70 n--; 71 72 int parent = 0; 73 int child = parent * 2 + 1; 74 while (child < n) { 75 if (child + 1 < n && heap[child] > heap[child + 1]) child++; 76 if (heap[parent] <= heap[child]) break; 77 pop_count++; 78 int t = heap[child]; 79 heap[child] = heap[parent]; 80 heap[parent] = t; 81 parent = child; 82 child = parent * 2 + 1; 83 // System.Console.WriteLine ("popの実行回数は{0}回です.", pop_count); 84 } 85 System.Console.WriteLine ("popの実行回数は{0}回です.", pop_count); 86 return minValue; 87 88 } 89 90}
試したこと
Main関数の方でSystem.Console.WriteLineしましたが、
The name push_count' does not exist in the current context The name
pop_count' does not exist in the current context
のエラーが出て困っています。ネットでも調べましたが、解決できませんでした。
補足情報(FW/ツールのバージョンなど)
初歩的な質問ですが、御教授いただけるとありがたいです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/03 12:40