[PYTHON] I tried to generate a random character string

Introduction

We have implemented programs in several languages that generate random strings (6 lowercase letters this time). The skill of the author of the article is almost the same as an amateur learning programming by himself. There is a code description in the article, but I would appreciate it if you could comment if there are any strange parts or anti-patterns.

table of contents

  1. [I wanted to make my own app name on Heroku](I wanted to make my own app name on #heroku)
  2. Implementation
  3. [C](# 1-c language)
  4. C++
  5. Python
  6. Ruby
  7. PHP
  8. Node.js
  9. Swift
  10. [Shell Script](# 8-Shell Script)
  11. [JavaScript (HTML embedded)](# 9-javascript html embedded)
  12. [Implementation Summary](# 10-Implementation Summary)
  13. Conclusion
  14. [At the end](#At the end)

I wanted to make my own app name on Heroku

The other day, I used Heroku for the first time. It's very easy to use, but I don't know what the app is from the automatically generated app name. It seems that you have to avoid duplication with the app name on Heroku to give it an arbitrary app name. As a simple method, use a naming convention

** Random string-app-name (ex. Fjofez-hello-app) **

If so, you can give it a name that is easy to understand while reducing the possibility of duplication. Therefore, I decided to write a program that generates a random character string in multiple languages. By the way, there are the following restrictions on the app name.

$ heroku rename MyApp
Renaming Old-App to NewyApp... !
▸ Name must start with a letter, end with a letter or digit and can 
  only contain lowercase letters, digits, and dashes.

`Names must start with a letter and end with a letter or number and can only contain lowercase letters, numbers, and dashes. ``

In addition, the maximum number of characters seems to be 30 characters. Random string generation was implemented with the following pattern.

** C, C ++, Python, Ruby, PHP, Node.js, Swift, Shell, JavaScript (HTML embedded) **

If you don't have time, skip to Conclusion.

Implementation

** Implementation rules ** are roughly as follows.

** Execution environment ** (Windows)

OSWindows 10 Home (64bit)
WSLUbuntu 18.04.4 LTS
Shell bash

** Execution environment ** (Mac)

OSCatalina 10.15.6
shell zsh

1. C language

When I was a student, I took one C language class and learned about a month on the entrance examination of an engineer school called 42Tokyo. In my mind, programming is the image of C language.

random_strings.c


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int num_of_char = 6;
    srand((unsigned int)time(NULL));

    for (int i = 0; i < num_of_char; i++)
        printf("%c", (rand() % 26 + 'a'));
    printf("\n");
}
$ gcc random_strings.c
$ ./a.out
ucxjvx
$ ./a.out
asuprq
$ ./a.out
rveroj

reference [Introduction to C language] How to use random numbers (rand)

  1. C++

I studied C ++ to participate in the contest at a service that holds a competitive programming contest called AtCoder. When you start programming, I think competitive programming is a great introduction for those who like puzzles.

random_strings.cpp


#include <iostream>
#include <random>
using namespace std;

int main()
{
    int num_of_char = 6;

    mt19937 mt{random_device{}()};
    uniform_int_distribution<int> dist(0, 25); // 26 letters of a~z

    for (int i = 0; i < num_of_char; i++)
        cout << char(dist(mt) + 'a');
    cout << endl;
}
$ g++ random_strings.cpp
$ ./a.out
zotuxm
$ ./a.out
faoxwv
$ ./a.out
czoxwt

reference C ++ random number library is difficult to use 3. Python

Everyone loves Python. I have hardly touched it. The amount of description is smaller than that of C language. There were many references.

random_strings.py


import random
import sys

for i in range(6):
    sys.stdout.write(chr(random.randrange(26) + ord("a")))
print("")
$ python random_strings.py
prnsro
$ python random_strings.py
nnaydv
$ python random_strings.py
uzejcc

reference Random to generate random decimals / integers in Python, randrange, randint, etc. [Python] Data types and casts Python Tips: I want to output a character string without line breaks Python Snippets

  1. Ruby

I'm working on a Rails tutorial. I wrote this article because I used Heroku in the Rails tutorial. The amount of code is just one line. It feels like a skin, but I feel that the execution speed is slow.

random_strings.rb


puts (0..5).map{ ("a".ord + rand(26)).chr }.join
$ ruby random_strings.rb
xgrqye
$ ruby random_strings.rb
cvijok
$ ruby random_strings.rb
ifmiau

** Added on 2020.9.5 ** In the comments, I learned how to write the code a little shorter. It is short and extensible (including numbers and uppercase letters).

python


puts (1..6).map{ [*"a".."z"].sample }.join

reference How to generate a random string in Ruby Convert Integer and characters with Ruby Array # sample (Ruby 2.7.0 Reference Manual)

  1. PHP

It was almost the first time I ran PHP from the command line. It's refreshing to add $ to the variable.

random_strings.php


<?php
    for ($i = 0; $i < 6; $i++)
        echo substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 1);
    echo "\n"
?>
$ php random_strings.php
fclvjt
$ php random_strings.php
mcttjp
$ php random_strings.php
rdvole

** Revised 2020.9.5 ** The part pointed out in the comment has been corrected. Corrected the number of characters in the generated character string to 8 characters => 6 characters No duplication => Corrected to have duplication

Before modification </ summary>


It was almost the first time I ran PHP from the command line. The amount of code is actually one line.

random_strings.php


<?php
    echo substr(str_shuffle('abcdefghijklmnopqrstuvwxyz'), 0, 8) . "\n";
?>
$ php random_strings.php
fwuxjhel
$ php random_strings.php
fcxmuypb
$ php random_strings.php
qkswgyjp

reference [How to run PHP on the command line [for beginners] Generate random password in one line

  1. Node.js

I touched it for the first time. It feels like I used Node.js to execute JavaScript from the command line rather than Node.js. I touched JavaScript itself a little when I was studying web production.

random_strings.js


'use strict';
function make_random_string() {
    const num_of_char = 6;
    let random;
    let str1 = "";
    for (let i = 0; i < num_of_char; i++)
    {
        random = Math.floor( Math.random () * 26 + "a".charCodeAt(0));
        str1 += String.fromCharCode(random);
    }
    console.log(str1);
}
make_random_string();
$ node random_strings.js
fpysdy
$ node random_strings.js
hshgzk
$ node random_strings.js
bedysa

reference Used from the introduction of Node.js in WSL environment JavaScript reverse lookup that can be used with copy / paste Get random numbers with javascript Convert characters to ASCII code with JavaScript

  1. Swift

I touched it for the first time. Basically, it was the language for making iOS apps, so I had the hardest time with this implementation. I feel that Swift is not suitable for implementation contents like this time.

random_strings.swift


let str = "abcdefghijklmnopqrstuvwxyz"

var i = 0
while i < 6 {
    let randomAlpha = Int.random(in: 0..<26)
    let fromIdx = str.index(str.startIndex, offsetBy: randomAlpha)
    let toIdx = str.index(str.endIndex, offsetBy: randomAlpha - 26)
    print(str[fromIdx...toIdx], terminator: "")
    i += 1
}
print("")
$ swift random_strings.swift
xwjrxd
$ swift random_strings.swift
pwqziz
$ swift random_strings.swift
psbhww

reference [Swift] How to generate random numbers How to get the string of index specified in Swift Repeat processing! How to use while / for statements written in Swift [for beginners]

8. Shell script

The shell script is created by google each time it is necessary for efficiency, and after 3 days it is a skill level that I forget.

random_strings.sh


#!/bin/bash
cat /dev/urandom | tr -dc 'a-z' | fold -w 6 | head -n 1
$ bash random_strings.sh
udhmsd
$ bash random_strings.sh
loxtxt
$ bash random_strings.sh
zxrbbe

reference Generate a random character string

9. JavaScript (HTML embedded)

Browser Version
Google Chrome Version: 84.0.4147.135
Microsoft Edge Version 85.0.564.44
Firefox Version: 80.0.1
Safari Version: 13.1.2

I just embedded the code implemented in Node.js into HTML. I'm ignoring the method because it's combined into one html file. If you move for the time being, it's OK. From an amateur's point of view, JavaScript that can be executed with a browser is convenient.

random_strings.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        html {background: #f7f7f7;}
        body {margin: 48px auto 0; padding-top: 12px; padding-left: 24px;}
        body {background: #fff; border: solid 1px #333; width: 640px;}
        .result {color: #F06060; font-size: 30px; font-weight: bold; margin-left: 2rem;}
        div {border-bottom: solid 2px #333; width: 300px;}
    </style>
</head>
<body>
    <h1>Generate a random string with JavaScript</h1>
    <div>
        <script>
            'use strict';
            function make_random_string() {
                const num_of_char = 6;
                let random;
                let str1 = "";
                for (let i = 0; i < num_of_char; i++)
                {
                    random = Math.floor( Math.random () * 26 + "a".charCodeAt(0));
                    str1 += String.fromCharCode(random);
                }
                console.log(str1);
                document.write("<span>Generated string=> </span>");
                document.write("<span class = result>" + str1 + "</span>");
            }
            make_random_string();
        </script>
    </div>
    <p>(a ~6 characters with duplicates from z)</p>
    <p>console.It is also displayed in the log.</p>
</body>
</html>

Check JavaScript (HTML embedding) with a browser (Microsoft Edge) js_edge.PNG

10. Implementation summary

I ran it on a Windows machine except Swift, but it was very easy to set up the environment thanks to WSL. When I was a student, I remember having a hard time setting up a C language development environment on a Windows machine. In addition, cloud IDEs such as AWS Cloud 9 are now available, and I feel that the environment is very blessed, as it is relatively easy to prepare a development environment even for joint development using docker.

Conclusion

Easy and fastest by hand. (In the example below, I hit the keyboard properly)

$ heroku rename wojwpd-hello-app

If you are wearing it, you can give it a different name.

Besides, I think that just adding a fixed word to the prefix will not duplicate it.

$ heroku rename apple-hello-app

At the end

It was a good experience to be exposed to various languages. If you're not happy with Hello World, why not try generating a random string as a starting point for your new language?

that's all.

Recommended Posts

I tried to generate a random character string
I want to split a character string with hiragana
I tried to automatically generate a password with Python3
I tried to sort a random FizzBuzz column with bubble sort.
I tried to create a linebot (implementation)
I tried to create a linebot (preparation)
I tried to make a Web API
I tried to build a super-resolution method / ESPCN
I tried to build a super-resolution method / SRCNN ①
I implemented DCGAN and tried to generate apples
I tried to debug.
I tried to paste
I tried to build a super-resolution method / SRCNN ③
I tried to build a super-resolution method / SRCNN ②
[Question] I want to scrape a character string surrounded by unique tags!
I tried to make a ○ ✕ game using TensorFlow
I tried to automatically generate a port management table from Config of L2SW
[Python] I tried to get the type name as a string from the type function
I tried to make a "fucking big literary converter"
I want to embed a variable in a Python string
I tried to create a table only with Django
I want to generate a UUID quickly (memorandum) ~ Python ~
I tried to draw a route map with Python
[Python] How to expand variables in a character string
I tried to implement a pseudo pachislot in Python
I tried to implement a recommendation system (content-based filtering)
[Go + Gin] I tried to build a Docker environment
I tried to draw a configuration diagram using Diagrams
I tried to summarize the string operations of Python
I tried to learn PredNet
I tried to organize SVM.
I tried using Random Forest
I tried to implement PCANet
I tried to reintroduce Linux
I tried to introduce Pylint
I tried to summarize SparseMatrix
I tried to touch jupyter
I tried to implement StarGAN (1)
I tried to implement a basic Recurrent Neural Network model
I tried to implement a one-dimensional cellular automaton in Python
I tried to automatically create a report with Markov chain
I want to automatically generate a modern metal band name
[Markov chain] I tried to read a quote into Python.
I made a command to generate a table comment in Django
I tried "How to get a method decorated in Python"
I tried to get started with Hy ・ Define a class
I want to convert an ISO-8601 character string to Japan time
I tried to automate [a certain task] using Raspberry Pi
I stumbled when I tried to install Basemap, so a memorandum
Python learning basics ~ How to output (display) a character string? ~
I tried to create a bot for PES event notification
I tried to make a stopwatch using tkinter in python
I tried to divide with a deep learning language model
I tried to make a simple text editor using PyQt
I tried to automatically generate OGP of a blog made with Hugo with tcardgen made by Go
I tried using PI Fu to generate a 3D model of a person from one image
I tried to implement Deep VQE
I tried to create Quip API
I tried to touch Python (installation)
Is it a character string operation?
I tried to implement adversarial validation