Comment detail

文字列の均等分割 (Nested Flatten)

ごくごく普通ですが、 C#が無かったので。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;

namespace bunkatsu
{
    class Program
    {
        static void Main(string[] args)
        {
            string sample = "ゆめよりもはかなき世のなかをなげきわびつゝあかしくらすほどに四月十よひにもなりぬれば木のしたくらがりもてゆく";

            divid(4, sample);
            divid(5, sample);
            divid(6, sample);
        }

        static public void divid(int n, string s)
        {
            int[] counts = new int[n];

            for (int i = 0, j = 0; i < s.Length; ++i, ++j)
            {
                if (j >= n)
                    j = 0;

                counts[j]++;
            }

            int start = 0;

            for (int i = 0; i < n ; ++i)
            {
                Console.WriteLine( s.Substring( start, counts[i] ) );
                start += counts[i];
            }
        }
    }
}

C++のまちがった例を書いてしまったので、書き直しました。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>
#include <iterator>
#include <locale>

using namespace std;

void divid(size_t size, const wchar_t* str) {
  vector<size_t> lengths(size);
  const wchar_t* p = str;
  for ( int i = 0; *p != L'\0'; ++p, ++i ) {
    if ( i == size )  i = 0;
    ++lengths[ i ];
  }

  vector<size_t>::const_iterator
    i = lengths.begin(),
    e = lengths.end();
  for ( ; i != e; ++i ) {
    wcout << wstring(str, *i) << endl;
    str += *i;
  }
}

int main() {
  locale::global(locale(""));
  const wchar_t* sample = L"ゆめよりもはかなき世のなかをなげきわびつゝ"
    "あかしくらすほどに四月十よひにもなりぬれば木のしたくらがりもてゆく";
  divid(4, sample);
  divid(5, sample);
  divid(6, sample);
  return 0;
}

Index

Feed

Other

Link

Pathtraq

loading...