HackerRank Building a Smart IDE: Identifying comments Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Building a Smart IDE: Identifying comments Solution. This problem is a part of the Regex HackerRank Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the  Regex HackerRank Solutions using  CPP, JAVA, PYTHON, JavaScript & PHP Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Building a Smart IDE: Identifying comments Solution
HackerRank Building a Smart IDE: Identifying comments Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Building a Smart IDE: Identifying comments Solution

Problem

Jack wants to build an IDE on his own. Help him build a feature which identifies the comments, in the source code of computer programs. Assume, that the programs are written either in C, C++ or Java. The commenting conventions are displayed here, for your convenience. At this point of time you only need to handle simple and common kinds of comments. You don’t need to handle nested comments, or multi-line comments inside single comments or single-comments inside multi-line comments.

Your task is to write a program, which accepts as input, a C or C++ or Java program and outputs only the comments from those programs. Your program will be tested on source codes of not more than 200 lines.

Comments in C, C++ and Java programs

Single Line Comments:

// this is a single line comment
x = 1; // a single line comment after code

Please note that in the real world, some C compilers do not necessarily support the above kind of comment(s) but for the purpose of this problem lets just assume that the compiler which will be used here will accept these kind of comments.

Multi Line Comments:

/* This is one way of writing comments / / This is a multiline
comment. These can often
be useful*/

Input Format
Each test case will be the source code of a program written in C or C++ or Java.

Output Format
From the program given to you, remove everything other than the comments.

Sample Input #00

// my  program in C++

#include <iostream>
/** playing around in
a new programming language **/
using namespace std;

int main ()
{
  cout << "Hello World";
  cout << "I'm a C++ program"; //use cout
  return 0;
}

Sample Output #00

// my program in C++
/** playing around in
a new programming language **/
//use cout

Sample Input #01

/This is a program to calculate area of a circle after getting the radius as input from the user/

include

int main()
{
double radius,area;//variables for storing radius and area
printf(“Enter the radius of the circle whose area is to be calculated\n”);
scanf(“%lf”,&radius);//entering the value for radius of the circle as float data type
area=(22.0/7.0)pow(radius,2);//Mathematical function pow is used to calculate square of radius printf(“The area of the circle is %lf”,area);//displaying the results getch(); } /A test run for the program was carried out and following output was observed
If 50 is the radius of the circle whose area is to be calculated
The area of the circle is 7857.1429*/

Sample Output #01

/This is a program to calculate area of a circle after getting the radius as input from the user/
//variables for storing radius and area
//entering the value for radius of the circle as float data type
//Mathematical function pow is used to calculate square of radius
//displaying the results
/A test run for the program was carried out and following output was observed If 50 is the radius of the circle whose area is to be calculated The area of the circle is 7857.1429/

Precautions
Do not add any leading or trailing spaces. Remove any leading white space before comments, including from all lines of a multiline comment. Do not alter the line structure of multi-line comments except to remove leading whitespace. i.e. Do not collapse them into one line.

HackerRank Building a Smart IDE: Identifying comments Solution in Cpp

#include<iostream>
using namespace std;
int main()
{
	string line;
	bool multi=false;
	while(getline(cin,line))
	{
		bool printed=false;
		bool single=false;
		for(int i=0;i<line.length();i++)
		{
			if(line[i]=='/'&&line[i+1]=='/'&&!multi) single=true;
			else if(line[i]=='/'&&line[i+1]=='*') multi=true;
			if(single||multi) {cout<<line[i];printed=true;}
			if(line[i-1]=='\n'&&single) single=false;
			else if(line[i]=='/'&&line[i-1]=='*'&&multi) multi=false;
		}
		if(printed) cout<<endl;
		printed=false;
	}
}

HackerRank Building a Smart IDE: Identifying comments Solution in Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.util.Arrays;

public class Solution {
	static BufferedReader br;
	static PrintWriter out;
	static String INPUT = "";
	
	static void solve() throws Exception
	{
		StringBuilder sb = new StringBuilder();
		while(true){
			String line = br.readLine();
			if(line == null)break;
			sb.append(line).append("\n");
		}
		char[] s = sb.toString().toCharArray();
		int n = s.length;
		boolean multiline = false;
		boolean singleline = false;
		int start = -1;
		for(int i = 0;i < s.length;i++){
			if(!multiline && !singleline && i+1 < n && s[i] == '/' && s[i+1] == '*'){
				multiline = true;
				start = i;
				i++;
			}else if(multiline && !singleline && i+1 < n && s[i] == '*' && s[i+1] == '/'){
				multiline = false;
				out.println(new String(s, start, (i+1)-start+1));
			}else if(!multiline && !singleline && i+1 < n && s[i] == '/' && s[i+1] == '/'){
				singleline = true;
				start = i;
				i++;
			}else if(singleline && s[i] == '\n'){
				singleline = false;
				out.println(new String(s, start, i-1-start+1));
			}
		}
	}
	
	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		br = new BufferedReader(INPUT.isEmpty() ? new InputStreamReader(System.in) : new StringReader(INPUT));
		out = new PrintWriter(System.out);
		
		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}
	
	static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}

HackerRank Building a Smart IDE: Identifying comments Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
import collections
import re

def get_input():
    import sys
    return sys.stdin.read()

TEXT = get_input()

Token = collections.namedtuple('Token', ['typ', 'value', 'line', 'column'])

def get_comments(s):
    # Tokenizing the text
    token_specification = [
        ('COMMENT_SINGLE_START',  r'//'),
        ('COMMENT_SINGLE_END', r"\n"),
        ('COMMENT_MULTI_START',  r'/\*'),
        ('COMMENT_MULTI_END',  r'\*/'),
        ('QUOTE', r'"')
    ]
    # Single regex match...
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)

    line = 1
    pos = line_start = 0
    in_single = in_multi = in_string = False
    single_start = None
    multi_start = None
    string_start = None

    for match in re.finditer(tok_regex, s):
        typ = match.lastgroup
        if not (in_multi or in_single) and typ == "QUOTE":
            in_string = not in_string
        elif not (in_multi or in_string) and not in_single and typ == "COMMENT_SINGLE_START":
            in_single = True
            single_start = match.start()
        elif not (in_multi or in_string) and in_single and typ == "COMMENT_SINGLE_END":
            in_single = False
            yield s[single_start:match.start()]
            single_start = None
        elif not (in_single or in_string) and not in_multi and typ == "COMMENT_MULTI_START":
            in_multi = True
            multi_start = match.start()
        elif not (in_single or in_string) and in_multi and typ == "COMMENT_MULTI_END":
            in_multi = False
            yield s[multi_start:match.end()]
            multi_start = None

for comment in get_comments(TEXT):
    print (comment)

HackerRank Building a Smart IDE: Identifying comments Solution in JavaScript

function processData(input) {
    var m,i;
    m = input.match(/\/\/.*$|\/\*(?:.|\n)*?\*\//gm)
    if (m){
        for (i=0;i<m.length;i++){
            console.log(m[i]);
        }
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

HackerRank Building a Smart IDE: Identifying comments Solution in PHP

<?php
$file = file_get_contents("php://stdin");
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
preg_match_all('/\/\*[\s\S]*?\*\/|\/\/.*/',$file,$matches);
echo implode($matches[0],"\n");
?>

Disclaimer: This problem (Building a Smart IDE: Identifying comments) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedia


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment