開発環境
- OS X Mavericks - Apple (OS)
- Dart Editor (開発環境)
- Dartium | Dart/ Structured web apps (ブラウザ, Dart VM 用 (Chromium with the Dart VM))
- Safari (ブラウザ, JavaScript 用)
- Dart (プログラミング言語)
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の8章(ファイル処理)、8.8(練習問題)、3.をDartで解いてみる。
その他参考書籍
- What is Dart? [Kindle版] (O'Reilly Media) Kathy Walrath Seth Ladd (著) このブログでの感想
8.8(練習問題)、3.
コード
sample.dart
import 'dart:html';
void main(){
var run = querySelector('#run'),
clear = querySelector('#clear'),
pre0 = querySelector('#pre0'),
reader = new FileReader();
InputElement input = querySelector('#f0');
input.accept = 'text/*';
run.onClick.listen((MouseEvent event){
var result = window.navigator.userAgent + '\n';
try {
File file = input.files[0];
reader.readAsText(file);
reader.onLoad.listen((Event event){
String text = reader.result;
result += '元のテキスト\n';
result += '$text\n';
for (var item in readWeatherData(text, fields)){
result += '$item\n';
}
result += 'ラッパー関数\n';
for (var item in readWeatherDataWrapper(text)){
result += '$item\n';
}
pre0.text = result;
});
} catch (e){
result += e.toString();
pre0.text = result;
}
});
clear.onClick.listen((MouseEvent event) => pre0.text = '');
}
List<List<List>> fields = [[[4, 'int'], [2, 'int'], [2, 'int']],
[[2, 'int'], [2, 'int'], [2, 'int']],
[[2, 'int'], [2, 'int'], [2, 'int']],
[[6, 'double'], [6, 'double'], [6, 'double']]];
List<List<List<num>>> readWeatherDataWrapper(String s){
List<List<List>> fields =
[[[0, 'int'], [4, 'int'], [6, 'int']],
[[8, 'int'], [10, 'int'], [12, 'int']],
[[14, 'int'], [16, 'int'], [18, 'int']],
[[20, 'double'], [26, 'double'], [32, 'dobule']]];
List<List<List>> new_fields = [];
List<List> new_field = [];
bool flag1 = true;
int temp_i = 0;
String temp_target_type = '';
for (List<List> field in fields){
bool flag2 = true;
for (List group in field){
int i = group[0];
String target_type = group[1];
if (flag1){
flag1 = false;
flag2 = false;
} else {
new_field.add([i - temp_i, temp_target_type]);
if (flag2){
new_fields.add(new_field);
new_field = [];
flag2 = false;
}
}
temp_i = i;
temp_target_type = target_type;
}
}
List<String> lines = s.split('\n');
new_field.add([lines.first.length - temp_i, temp_target_type]);
new_fields.add(new_field);
return readWeatherData(s, new_fields);
}
List<List<List<num>>> readWeatherData(String s, List<List<List>> fields){
List<List<List<num>>> result = [];
s = s.trim();
List<String> lines = s.split('\n');
for(String line in lines){
int start = 0;
List record = [];
for(List field in fields){
List<num> group = [];
for (List f in field){
int width = f[0];
String t = f[1];
String text = line.substring(start, start + width);
num value = t == 'int' ? int.parse(text) : double.parse(text);
group.add(value);
start += width;
}
record.add(group);
}
result.add(record);
}
return result;
}
0 コメント:
コメントを投稿