言語処理100本ノック04(C#、Java)

04. 元素記号

"Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can."という文を単語に分解し,1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字,それ以外の単語は先頭に2文字を取り出し,取り出した文字列から単語の位置(先頭から何番目の単語か)への連想配列(辞書型もしくはマップ型)を作成せよ.

C#

using System;
using System.Collections.Generic;
using System.Linq;

public class Hello{
    public static void Main(){
        var text = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.";
        var words = text.Split(' ');
        
        //1, 5, 6, 7, 8, 9, 15, 16, 19番目の単語は先頭の1文字
        int[] positionA = {1, 5, 6, 7, 8, 9, 15, 16, 19};
        //それ以外の単語は先頭に2文字
        
        Dictionary<string, int> result = new Dictionary<string, int>();
        int i=1;
        foreach(var word in words){
            string symbol = null;
            int position = 0;
            if(Array.IndexOf(positionA, i) != -1){
                //最初の1文字を取得
                symbol = word.Substring(0, 1);
                position = 1;
            }else{
                //最初の2文字を取得
                symbol = word.Substring(0, 2);
                position = 2;
            }
            result.Add(symbol, position);
            i++;
        }
    }
}

Java

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {

        String target = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.";
        String[] targetArray = target.split(" ");
        List<Integer> firstChar = Arrays.asList(1, 5, 6, 7, 8, 9, 15, 16, 19);
        
        Map<String, Integer> result = new HashMap<>();
        for(int i=0; i<targetArray.length; i++)
        {
            var item = targetArray[i];
            if(firstChar.contains(i+1)){
                result.put(item.substring(0, 1), i+1);
            }else{
                result.put(item.substring(0, 2), i+1);
            }
        }
    }
}