Problem 20. linerasearch.js ( mark == false is introduced , lecture 7 timestamp 42:10)

 /*Question

Given a sequence of integers and a query integer, find out if the query integer is present or
not.

Input:
First line containing a positive integer , say q, denoting the query integer.
2nd line contains a positive integer say n, denoting the length of the sequence.
Next n line contains one integer each, denoting the elements of the sequence.

Output:
one line containing present or not present.

Example:
Input 1
67
4

23
24
45
12

Output 1
Not present

Input 2
27
5

74
20
27
54
-45

Algorithm:
1.Read the query number.
2.Read the length of the sequence .
3.Run the loop till length of the sequence.
4.Read the number from the sequence , then check if equal to query integer.
5.If found break.
6.Else go and read the next number in the sequence and repeat step 4 and 5.
*/

let fs = require("fs");
let data = fs.readFileSync(0, 'utf-8');
let idx = 0;
data = data.split('\n');

function readLine() {
idx++;
return data[idx - 1].trim();
}
//..............................................................................................................................

let queryInteger = parseInt(readLine()); // 67

let lengthOfSequence = parseInt(readLine()); // 4

let mark = false; // we are assuming that we haven't found the query integer

let i = 0; // this is the intilization for whilenloop

while (i < lengthOfSequence) {
let integers = parseInt(readLine());

if (integers == queryInteger) {
console.log('Present');

mark = true; // this means we have found our query integer

break;// so we break entirely from the loop

}

i++ // this is the increment for while loop

}

if (mark == false) // which means we haven't found any queryInteger in the loop
{
console.log('Not Present');

}

Terminal for first test case:
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$ node linearsearch.js <input.txt Not Present
----------------------------------------------------------------------------------------------

Terminal for 2nd test case:
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$ node linearsearch.js <input.txt
Present
Nobins-MacBook-Pro:STOC_MODULE 11SEPT 2022 nobinpunyo$ 

Comments

Popular posts from this blog

Problem 33. patter122333.js

Problem 38. diamond.js

Problem 16. chocolatebills.js