LoginSignup
82
36

More than 3 years have passed since last update.

ホクホクのイモ

Last updated at Posted at 2019-07-02

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 さんに教えて貰った)

82
36
29

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
82
36