Help us understand the problem. What is going on with this article?

ホクホクのイモ

More than 1 year has passed since last update.

Goで書くとこうなるやつの話。

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    s := ""
    rs := []rune("ホイクモ")
    for _, j := range rand.Perm(4)[:2] {
        s += string(rs[j])
    }
    s += s + "の"
    for _, j := range rand.Perm(4)[:2] {
        s += string(rs[j])
    }
    fmt.Println(s)
}

実行結果

ホクホクのクホ
ホイホイのイモ
イモイモのモイ

C++ だとこうなる

#include <algorithm>
#include <iostream>
#include <vector>
#include <locale>
#include <iterator>
#include <random>
#include <codecvt> 

std::string
wstring2string(std::wstring& w) {
  std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> cv;
  return cv.to_bytes(w);
}

int
main() {
  std::random_device seed_gen;
  std::mt19937 engine(seed_gen());

  std::wstring out;

  std::wstring hokuimo = L"ホクイモ";
  std::shuffle(hokuimo.begin(), hokuimo.end(), engine); 
  out = hokuimo.substr(0, 2);
  std::shuffle(hokuimo.begin(), hokuimo.end(), engine); 
  out += out + L"の" + hokuimo.substr(0, 2);
  std::cout << wstring2string(out) << std::endl;
  return 0;
}

※ mingw でも実行できる様に wout を使わない様にしています。実行結果は utf-8

Perl だとこう

use strict;
use warnings;
use utf8;
use List::Util qw/shuffle/;  

binmode STDOUT, ':encoding(utf-8)';
my @hokuimo = split('', 'ホクイモ');
my $hoku = join('', (shuffle(@hokuimo))[0..1]);
my $imo = join('', (shuffle(@hokuimo))[0..1]);
print "${hoku}${hoku}${imo}";

やはりこういうのを書かせると Ruby の良さは際立つなぁと思いました。

puts '%1$s%1$sの%2$s'%((%w[ホイクモ]*2).map{|x|x.chars.sample(2).join})

(1$ は ujihisa さんに教えて貰った)

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away