Hacker Rank Exercise For Asterisks square - javascript

I'm currently doing this exercise, and as far as I know, the code is correct.
However, for some reason HackerRank is either, saying that result is Not a Number(NaN), or there is not output on sdtout.
I have no idea what to do.
I know this have something to deal with the fact that HackerRank has an "expected" way of writing the code, so it can pass the values, but I don't understand.
e.g. quadrado means square, and linha line.
The function prints an square of asterisks.
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
function imprimaQuadradoAsterisco(n) {
// não altere a linha acima
/*
* Escreva nas linhas a seguir um código que
* imprima um quadrado de asteríscos
* de altura e largura igual ao valor de n
*/
if ( n >= 0){
let asterisco = "*";
let linha = asterisco * n;
let quadrado = "";
for (let i = 0; i < n; i++){
quadrado += linha + "\n";
}
return quadrado;
} else {
return "Somente números maiores ou igual a 0";
}
console.log(imprimaQuadradoAsterisco(n));
// não altere a linha abaixo
}
// fim do seu código
I tried many ways of doing the code, however my problem is how hackerrank deals with the input of information for the code. I don't think the problem is necessary the code itself, but might be wrong.

You cannot use the multiplication operator (*) to repeat strings (like you can in Python). Instead, use String#repeat.
let linha = asterisco.repeat(n);

Related

Is it possible to get a variable or localStorage value to insert in a Web SQL code?

I've created just a simple code to simulate a virtual store with HTML, Web SQL & Javascript language and my question is: Is it possible to get a variable or localStorage value to insert in a Web SQL code?
I just need to change the code number "100013" below by a variable or localStorage item.
var bdd = openDatabase("bdLojaVirtual", "2.0", "LojaVirtual", 2000000);
var mostrar;
var button = document.getElementById("pesquisar");
button.onclick = function consultarProduto() {
var produto = document.getElementById("codigo").value;
produto = produto;
localStorage.setItem("Item selecionado", produto);
}
bdd.transaction(function (selecionar) {
var produto = localStorage.getItem("Item selecionado");
selecionar.executeSql ('SELECT nome FROM produto WHERE codigo = 100013', [],
function (selecionar, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
mostrar = "<p><b>" + results.rows.item(i).nome + "</b></p>";
document.querySelector('#aqui').innerHTML += mostrar;
}
}, null);
});
The whole project is at https://github.com/jmlJunior/portifolioPessoal
After some research I got it: I've just replaced the code number "100013" by "?" and "[]" by "[produto]" and it works well.
bdd.transaction(function (selecionar) {
var produto = localStorage.getItem("Item selecionado");
selecionar.executeSql ('SELECT nome FROM produto WHERE codigo = ?', [produto],
function (selecionar, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
mostrar = "<p><b>" + results.rows.item(i).nome + "</b></p>";
document.querySelector('#aqui').innerHTML += mostrar;
}
}, null);
});

How to make redirection not random and follow the order?

I have this code with which I intend that every time the same user reloads the page it redirects it to a different URL, the problem is that sometimes it redirects to the same URL in the list and what I am looking for is to follow an order.
For example: url1, url2, url3.
var URLlist = ["url1.html", "url2.html", "url3.html"];
var reDelay = 0000;
setTimeout(function () {
window.location = URLlist[Math.floor(Math.random() * URLlist.length)];
}, reDelay);
You could check the current URL of the page by using window.location.href and filter it from the list of URL's. Then only the options that are not the current page can be selected as the new URL.
/**
* Example current URL.
* The value of this should be the URL of the current page.
* Like window.location.href
*/
var currentURL = 'url2.html';
// Filter the current page from the list.
var URLlist = ["url1.html","url2.html","url3.html"].filter(url => url !== currentURL);
var reDelay = 1000;
setTimeout(function(){
var newURL = URLlist[Math.floor(Math.random()* URLlist.length)];
// window.location = newURL;
console.log(newURL);
}, reDelay);
Maybe something like:
var URLlist = ["url1.html","url2.html","url3.html"];
//URLs a las que el usuario ha sido redireccionado.
var urlsRedireccionado = JSON.parse(window.localStorage.getItem("urls_redireccionado")) || [];
var reDelay = 0000;
setTimeout(function(){
//La siguiente URL en el orden en que han sido agregadas en la variable URLlist
var next = URLlist.find(u => !urlsRedireccionado.some(ur => ur == u));
//Si faltan URL por redireccionar
if(next) {
urlsRedireccionado.push(next);
window.localStorage.setItem("urls_redireccionado", JSON.stringify(urlsRedireccionado));
window.location = next;
} else {
//Para que la proxima vez que recargue sea redirigido a todas las URL anteriores
window.localStorage.removeItem("urls_redireccionado");
//Redireccionado a todas partes
}
}, reDelay);
Try adding a counter which will help you keep a track of URL position and a condition that will help you reset counter to the first position in the array when you are out of URLs.
var URLlist = ['url1.html', 'url2.html', 'url3.html'];
var counter = 0;
var reDelay = 2000;
setTimeout(function() {
window.location = URLlist[counter];
counter++;
URLlist[counter] === undefined ? counter = 0 : counter;
}, reDelay);

Calculate the total of form immediately without having to check a checkbox

I have an HTML, JavaScript form, which calculates a price based upon choices made in the form. The problem is that the total price will only be calculated after one checkbox has been clicked. I want it to calculate the price immediately without having to check a checkbox first. Below is a snippet of the JavaScript code:
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value); // this function should run immediately
}
}
document.getElementById("total").value = "€" + total.toFixed(2);
}
The full form can be found here.
How can this be done?
Call the totalIt(); after loading the page.
<!-- Rekenscript om het totaal van het formulier te genereren -->
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "€" + total.toFixed(2);
}
<!-- Checkbox switch om maandelijkse kosten aan of uit te doen -->
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for(var i=0;i<chboxs.length;i++) {
if(chboxs[i].checked){
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
<!-- Switch om ander thema te kiezen (met a href) -->
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Een ander thema kiezen";
}
else {
ele.style.display = "block";
text.innerHTML = "Huidige thema behouden";
}
}
totalIt(); // call it here
I have found a good solution. It is pretty stupid that I hadn't realised it, but unfortunately I am not that good at JavaScript.
I used the totalIt(); as #Durga suggested. I added this script around it, so that It would call the calculate function every 10ms:
window.setInterval(function(){
totalIt();
}, 10);
It doesn't matter where you place the script, as long as you don't place it in the form code, or replace any code. Of course you can change the 10ms to whatever you need. Thank you all for your answers.

javascript split and for functions

hi im trying to show multiple images with split ans for functios but im having problems:
the php returns a string with links separated by comas and i need to show as image each record this is the code:
var msg 'files/uploads/1688482n.jpg,files/uploads/10904912__n.jpg,files/uploads/10907098_0_o.jpg';
var img = explode(msg)
$('.mensage').html(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").val(""+msg+"");
}
function explode(t) {
var txt = t,
list = txt.split(","),
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+i+"'><br>")); //This gets its place
}
return tt
}
in return im having this in the console:
Resource interpreted as Image but transferred with MIME type text/html:
so how i can display each image right?
the problem is showing like this:
<img style="width:290px;height:190px;" class="img-tm2" src="0">
<img style="width:290px;height:190px;" class="img-tm2" src="1">
Your code has a few bugs. Here is a corrected code:
var msg = 'n.jpg,o.jpg';
var img = explode(msg);
$('.mensage').val(img);//A el div con la clase msg, le insertamos el mensaje en formato thml
$('.mensage').show('slow');//Mostramos el div.
$("#im").html(img);
function explode(txt) {
var list = txt.split(",");
tt = "";
console.log(list);
for (var i = 0; i < list.length; i++) {
tt += "<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br />"; //This gets its place
}
return tt;
}
Trying to enumerate them:
missing semicolons at the end of statements;
var msg = (missing "=");
i instead of list[i];
Why do you print i and not that ?
for (var i = 0; i < list.length; i++) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+list[i]+"'><br>")); //This gets its place
}
use for each instead of for loop.
for each(var url in list) {
(tt += ("<img style='width:290px;height:190px;' class='img-tm2' src='"+url+"'><br>")); //This gets its place
}
return tt
}

Updating final sheet without losing data

I have several sheets in the same spreadsheet, sheets with data to facilitate my job when i do my script that generates sheets that i need, and my problem is when i add more data, is there any solution to update the final sheet without losing what I wrote before .
My exemple : Every user I add the sheet of data, if I execute the function it'll add a timesheet with its name in final sheet, and I don't know how to keep the data i added in the timesheets of users because, as you know, the execution of the function will crush it and generate a new timesheet for all the users
Here is the code of the function that generates the timesheets:
function generateTimeSheet(){
Logger.clear();
var semaine=1;
var projectSheet = ss.getSheetByName("Liste Projets");
var usersSheet = ss.getSheetByName("Utilisateurs");
var tabProjectsLibs = getProjectList();
//Récupération de la liste des utilisateurs
var tabUsers = getUsersList();
//Suppression des colonnes vides
for(i = 1; i < 13; i++){
//Nombre de jours du mois
var date = new Date(i + "/01/" + year);
var nbDays = getNbJours(date);
//Nettoyage de la feuille
var currentMonthSheet = getSheetByMonth(tabMonth[i - 1]);
var rows = currentMonthSheet.getMaxRows();
var cols = currentMonthSheet.getMaxColumns();
var currentMonthRange = currentMonthSheet.getRange(rows, cols);
currentMonthSheet.clear();
currentMonthSheet.clearFormats();
//Suppression des lignes et colonnes inutiles
try{
currentMonthSheet.deleteColumns(2, cols - nbDays );
}catch(e){
//Logger.log("erreur : " + e);
}
try{
currentMonthSheet.deleteRows(2, rows - 3);
}catch(e){
//Logger.log("erreur : " + e);
}
var numProjects = getProjectNumber();
var prjLines = 2;
//Ajout des utilisateurs
//Ajout des entêtes et des tableaux par user
for(l = 0; l < tabUsers.length; l++){
var firstLine = 1 + (l+1)*10 - 10 + (l + 1) * numProjects - numProjects;
var nbTours = generateUserTimeSheet(tabUsers[l], firstLine, currentMonthSheet, nbDays, semaine);
prjLines = 2;
//Ajout des projets par user
for(m = 0; m < numProjects; m++){
addProject(tabProjectsLibs[m], firstLine + 5 + m, currentMonthSheet, prjLines, numProjects);
prjLines++;
}
}
semaine += nbTours;
}
}
My guess would be that removing these cleanup lines should do the trick.
currentMonthSheet.clear();
currentMonthSheet.clearFormats();
try{
currentMonthSheet.deleteColumns(2, cols - nbDays );
}catch(e){
//Logger.log("erreur : " + e);
}
try{
currentMonthSheet.deleteRows(2, rows - 3);
}catch(e){
//Logger.log("erreur : " + e);
}

Categories

Resources