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.
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 rules ** are roughly as follows.
** Execution environment ** (Windows)
OS | Windows 10 Home (64bit) |
---|---|
WSL | Ubuntu 18.04.4 LTS |
Shell th> | bash td> |
** Execution environment ** (Mac)
OS | Catalina 10.15.6 |
---|---|
shell th> | zsh td> |
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)
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
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)
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
It was almost the first time I ran PHP from the command line. The amount of code is actually one line.
Before modification </ summary>
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
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
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]
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
Browser th> | Version th> |
---|---|
Google Chrome td> | Version: 84.0.4147.135 td> |
Microsoft Edge td> | Version 85.0.564.44 td> |
Firefox td> | Version: 80.0.1 td> |
Safari td> | Version: 13.1.2 td> |
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)
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.
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
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