[JAVA] Let's rewrite the C language assignment of the university with Node.js

C is the first computer language to learn in your university department. When I asked a college student I knew, it seems that there are many C or Java. There are few samples, but ... As with myself, the first programming language is C. Classes range from basic syntax to pointer structures. Personally, I've recently started to get serious about proramming, writing Javascript, especially server-side Node.js. I will not touch on the pros and cons of doing C language at university, but it would be meaningful if someone who did C language at school found this article and asked, "Can I write this in Node.js?" I wonder if. I hope it will be an opportunity to write web applications after that. (Well, I wrote it almost capriciously, so I just tried to write it as an article ...)

Node.js

You can get as many details as you want by google, but officially there is this.

Node.js is a JavaScript environment that runs on Chrome's V8 JavaScript engine. Node.js employs an asynchronous event-driven model that is lightweight and works efficiently. Node.js's package management manager, npm, is the largest open source library ecosystem in the world.

Javascirpt is a browser-based language, but it can also be run on the server side using this platform. Furthermore, it has features such as asynchronous processing, event-driven type, and single thread, and is sometimes preferred from the viewpoint of processing speed. I think that accurate commentary articles are rolling around, so I will not explain in detail. Another thing to add is that you can use a lot of libraries with a package manager called npm, and you can implement what you want to do without writing too much code. While I was doing C language, I thought, "If this is such a difficult thing, it would be tremendous to develop an application ...". However, if it is a popular language, the library is extensive and you can easily do various things. Surprisingly, I don't know this, and when programming is difficult, I tend to be shy. Surprisingly, it is a fact that even if it is not good, it can be implemented only by abuse of copy and paste and library. Of course, I don't think this method is the best for learning. Whether it's good or bad, make something that moves and go up to the stage first. I think this is one correct answer, but I think. (Well ... I'm not a big fan, but ... Writing an article is one of the things that goes up on stage.) That's all for Node.js. If you want to check the operation, please install node on your PC.

Main subject: Rewrite C language

I will not explain in detail. One solution is that if you want to get the same result, you can do it like this.

Read file

A program that reads the file jinkou.txt, adds units to the population (people) and area (km2) of each prefecture, and outputs it to the display.

jinkou.txt is a plain text with the population area of 47 prefectures separated by tabs as shown below.

jinkou.txt


Aichi 7254704 5164.06
Ehime Prefecture 1467815 5677.38
Ibaraki Prefecture 2975167 6095.69
Okayama Prefecture 1957264 7113
Okinawa Prefecture 1361594 2275.28
Iwate Prefecture 1385041 15278.77
Gifu Prefecture 2107226 10621.17
.......
 

read-file.c


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

int main() {
	FILE *fp;
	char pref[256];
	int popu;
	float area;
	
  if((fp = fopen("jinkou.txt", "r")) == NULL) {
    printf("This file can not be opened\n");
    exit(1);
  }

  while (fscanf (fp , "%s", pref) != EOF) {
    fscanf(fp, "%d", &popu);
    fscanf(fp, "%f", &area);
    printf("%10s%10d people%10.2fKm2\n", pref, popu, area);
  }

  fclose(fp);
  return area;
}

result

Success if it is displayed on the console like this

Kobito.8mrvnq.png

With Node.js

It is an implementation that reads Stream. I think there are many other ways.

read-file.js


'use strict';
const fs = require('fs');
const readline = require('readline');
const rs = fs.createReadStream('./jinkou.txt');
const rl = readline.createInterface({ 'input': rs, 'output': {} });

rl.on('line', (lineString) => {
  const columns = lineString.split(' ');
  const pref = columns[0];
  const popu = parseInt(columns[1]);
  const area = parseInt(columns[2]);
  console.log(pref + "\t" + popu + 'Man' + "\t" + area + 'km2');
});

This will give similar results.

Writing a file

A program that outputs the population density of each prefecture to the file mitsudo.txt together with the prefecture name.

write-file.c


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

int main(void) {
	FILE *file1, *file2;
	char pref[256];
	int popu;
	float area, mitsudo;
	
  if ((file1 = fopen("jinkou.txt", "r")) == NULL) {
    printf("This file can not be opened\n");
    exit(1);
  }

  if ((file2 = fopen("mitsudo.txt", "w")) == NULL) {
    printf("This file can not be opened\n");
    exit(1);
  }

  while (fscanf (file1 , "%s", pref) != -1) {
    fscanf(file1, "%d", &popu);
    fscanf(file1, "%f", &area);
    mitsudo = (float)popu / area;
    fprintf(file2, "%8s %8.2f people/Km2\n", pref, mitsudo);
  }

  fclose(file1);
  fclose(file2);
}

result

If misudo.txt like this is displayed, it succeeds (as with jinkou.txt, the file name is not given by me, so it's not bad ...)

Kobito.TJ8Hog.png

With Node.js

write-file.js


'use strict';
const fs = require('fs');
const readline = require('readline');
const rs = fs.createReadStream('./jinkou.txt');
const rl = readline.createInterface({ 'input': rs, 'output': {} });
const map = new Map();

rl.on('line', (lineString) => {
  const columns = lineString.split(' ');
  const pref = columns[0];
  const popu = parseInt(columns[1]);
  const area = parseInt(columns[2]);
  const popu_density = (popu / area).toFixed(2) + 'Man/km2';
  map.set(pref, popu_density);
});

rl.on('close', () => {
  let data = "";
  map.forEach((value, key) => {
    data += key + '\t' + value + '\n';
  }, map);
  fs.writeFile('./mitsudo.txt', data, ({ encoding: 'utf-8' }), (err) => {
    if (err) throw err;
    console.log('The file has benn saved!');
  });
});

Search the contents of the file

Search for data that matches the prefecture name entered from the keyboard Program to output to the display

search-file.c


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

int main(void) {
	FILE *file1;
	char pref[50][256], dmy[80], indata[80];
	float mitsudo[50];
	int n = 0, kosuu;
	
  if ((file1 = fopen("jinkou.txt", "r")) == NULL) {
    printf("This file can not be opened\n");
    exit(1);
  }

  while (fscanf (file1 , "%s", pref[n]) != -1) {
    fscanf(file1, "%f", &mitsudo[n]);
    fscanf(file1, "%s", &dmy);
    ++n;
  }
  kosuu = n - 1;

  fclose(file1);
  
  while(indata[0] != 'q') {
    printf("Name of prefectures(End with q)=");
    gets(indata);
    //Search
    for (n = 0; n <= kosuu; ++n) {
      if (strcmp(pref[n], indata) == 0) {
        printf("%8s %8.2f people/Km2\n", pref[n], mitsudo[n]);
      }
    }
  }
}

result

Kobito.hhviSj.png

With Node.js

'use strict';
const fs = require('fs');
const readline = require('readline');
const rs = fs.createReadStream('./mitsudo.txt');
const rl = readline.createInterface({ 'input': rs, 'output': {} });
const map = new Map();

rl.on('line', (lineString) => {
  const columns = lineString.split('\t');
  const pref = columns[0];
  const popu_density = columns[1];
  map.set(pref, popu_density);
});

rl.on('close', () => {
  console.log('Please enter the prefecture name.(ctrl+End with c)');
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.on('data', (data) => {
    let a = data.slice(0, data.length - 1);
    console.log(a + "\t" + map.get(a));
  });
});

Impressions and summary

Unexpectedly, I couldn't write it so easily and shortly ... In terms of implementation, the specifications of process.stdin.on () are not well understood and \ n is included in the received value, so I stumbled on the point that it cannot be used as an argument of map.get () as it is. I had a hard time. Also, I wrote an article like this for the first time other than this report, I realized again that my writing was horribly verbose and long. Well, I don't think it's the number of outputs, so I'll continue to write something.

Recommended teaching materials for Node.js

I studied at N Preparatory School. I think the very easy-to-understand and polite teaching materials are very wonderful. If you do not understand the meaning of the code even after reading the official documents, we recommend that you take this course. Eventually, I was able to create a web application using the framework, so I enjoyed the content as well. I recommend you to say it again.

For the time being

https://github.com/takewell/c2node

Recommended Posts

Let's rewrite the C language assignment of the university with Node.js
Java language from the perspective of Kotlin and C #
Image processing: Let's play with the image
Android application: Let's explain the mechanism of screen transition with simple code
Let's express the result of analyzing Java bytecode with a class diagram
About the version of Docker's Node.js image
Check the contents of params with pry
Convert C language to JavaScript with Emscripten
About the treatment of BigDecimal (with reflection)
Format the contents of LocalDate with DateTimeFormatter
Try design patterns in C language! Memento pattern-Let's memorize the memories of the data
Let's refer to C ++ in the module of AndroidStudio other project (Java / kotlin)
[Code] Forcibly breaks through the C problem "* 3 or / 2" of [AtCoder Problem-ABC100] with Java [Code]