DEV Community

loading...

JavaScript Code Daily Challenge #5

Lakshya Tyagi
・1 min read

About

This is a series of JavaScript Code Daily Challenge. Each day I show a few solutions written in JavaScript. The questions are from coding practice/contest sites such as HackerRank, LeetCode, Codeforces, Atcoder and etc.

Designer PDF Viewer
https://www.hackerrank.com/challenges/designer-pdf-viewer/

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}
Enter fullscreen mode Exit fullscreen mode

Complete the function in comment

function designerPdfViewer(h, word) {


}
Enter fullscreen mode Exit fullscreen mode
function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const h = readLine().split(' ').map(hTemp => parseInt(hTemp, 10));

    const word = readLine();

    let result = designerPdfViewer(h, word);

    ws.write(result + "\n");

    ws.end();
}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
lakshyatyagi24 profile image
Lakshya Tyagi Author
function getIndex(char) {
    var alphabet = ['a', 'b', 'c', 'd', 'e',
        'f', 'g', 'h', 'i', 'j',
        'k', 'l', 'm', 'n', 'o',
        'p', 'q', 'r', 's', 't',
        'u', 'v', 'w', 'x', 'y',
        'z'];

    return alphabet.indexOf(char);
}
Enter fullscreen mode Exit fullscreen mode
function designerPdfViewer(h, word) {
    let wordHeight = [], maxVal = 0;
    for (let i = 0; i < word.length; i++) {
        wordHeight.push(h[getIndex(word[i])]);
    }

    maxVal = Math.max(...wordHeight);
    return (word.length * maxVal);

}
Enter fullscreen mode Exit fullscreen mode
Collapse
nahlagalal profile image
NahlaGalal

We can get index of character by using charCodeAt()

function designerPdfViewer(h, word) {
    let max = 0;
    for(let i in word) {
        const charIndex = word.charCodeAt(i) - 97;
        if(h[charIndex] > max) max = h[charIndex];
    }
    return max * word.length;

}
Enter fullscreen mode Exit fullscreen mode