imageIcon.js with less dry run( *** REVISE***)

 /*Image Icon Match

You are given a 1D image. The image is a sequence of pixel values.
You are also given an icon of a particular size.
The icon is a sequence of 2 pixels. Find the number of times this icon appears in the image.

Input
First line contains n, the number of pixels in the image.
This is followed by n lines, each containing one positive integer denoting a pixel, j, 0 <= j <= 255.
This is followed by m, the number of pixels in the icon.
This is follwoed by m lines, each containing one positive interger denoting a pixel k, 0 <= k <= 255.

Output
An integer i i >= 0, denoting the number of times the icon appears in the image.

Example
Input:

10
7
27
31
8
9
10
25
8
9
11
2
8
9
Output:

2
The first line is 10 i.e. 10 pixels in the given image 7, 27, 31, 8, 9, 10, 25, 8, 9, 11
is the given image After this, the line contains 2, i.e. 2 pixels in the icon 8, 9
is the given icon. 8, 9 appears twice in the image. So 2 is the answer.
*/

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();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This parts is only for taking input of Image
const noOfPixelsInImage = parseInt(readLine()); // 10 is the no. of pixels in the given image

let image = []; // we will push all the image elements in this array

for (let i = 0; i < noOfPixelsInImage; i++) {
image[i] = (parseInt(readLine()));

}
// console.log(image); [
// 7, 27, 31, 8, 9, yellow color elements
// 10, 25, 8, 9, 11
// ]

// This part is only for taking Inputs of Icon

const noOfPixelsInIcon = parseInt(readLine()); // 2 is the no. of pixels in the given icon

let icon = []; //we will add/push all the icon elements here.

for (let i = 0; i < noOfPixelsInIcon; i++) {

icon.push(parseInt(readLine()));

}
// console.log(icon); [ 8, 9 ] yellow color elements

// This part is the actual operation

let j = 0, i = 0; // J is the pointer for image and i is the pointer for icon and both i
// and j are intialisation for the while loop.

let count = 0; // since initially there is no count of icon in image

while (j < noOfPixelsInImage) {

if (image[j] == icon[i]) {

let x = j;

while (j < noOfPixelsInImage && image[j] == icon[i]) {
j++;
i++;
}

if (i >= icon.length) {
count++;
}

j = x + 1;
i = 0;
}

else { j++; }
}

console.log(count);

//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:




Comments