I just registered in HackerEarth and trying to solve the first basic problem: Monk and rotation. When I am running the code by entering single input it works fine but when I submit the solution it does not work.
https://www.hackerearth.com/practice/codemonk/
It seems I am reading the input incorrectly
Can someone please help.
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";
process.stdin.on("data", function (input) {
stdin_input += input; // Reading input from STDIN
});
process.stdin.on("end", function () {
let lines = stdin_input.split('\n');
let len = lines.length;
let inputArr = [];
const numberTestCase = lines[0]
const output = new Array()
for (i = 1; i < lines.length; i++) {
let lineInput = lines[i].split(' ');
let noOfElement = 0;
let stepRotation = 0;
let skipLineUpto = 0;
let inputData = false;
if (lineInput.length === 2) {
inputData = true;
noOfElement = lineInput[0]
stepRotation = lineInput[1]
skipLineUpto = parseInt(i) + 2;
}
if (inputData) {
let stringOfArray = lines[i + 1];
let arrayData = stringOfArray.split(' ');
let mod = 0
mod = stepRotation % noOfElement;
if (mod != 0) {
let unReversedArray = arrayData.splice(-mod);
let ff = unReversedArray.concat(arrayData)
inputArr.push(ff.join(' '))
} else {
let ff = arrayData
console.log(ff.join(' '))
inputArr.push(ff.join(' '))
}
}
}
main(inputArr)
});
function main(input) {
process.stdout.write(input.join("\n")); // Writing output to STDOUT
}
When you submit you can see why your code is not valid.
Your solution is for when scenarios where input is 3 lines (1 test case), like in their example, but you can see their test cases where they have inputs of multiple lines (T test cases).
Without any prototype method something like this would work (not working because time exceeded):
let lines = stdin_input.split('\n');
let loops = lines[0];
for(i = 1; i < lines.length; i+=2) {
let steps = lines[i].split(' ')[1];
let arr = lines[i+1].split(' ');
for (j = 0; j < steps; j++) {
var x = arr[arr.length-1], i;
for (k = arr.length-1; k > 0; k--) {
arr[k] = arr[k-1];
}
arr[0] = x;
}
main(arr);
}
With pop() and unshift() only one test case is failing due to time exceeded but should get you close to the final solution:
let lines = stdin_input.split('\n');
let loops = lines[0];
for(i = 1; i < lines.length; i+=2) {
let steps = lines[i].split(' ')[1];
let arr = lines[i+1].split(' ');
for (j = 0; j < steps; j++) {
arr.unshift(arr.pop());
}
main(arr);
}
My Concatenation function is running excruciatingly slow, on only 28 rows of data it takes almost 4 minutes to run and I have other code I need to run so I hit the Max execution time in Google sheets
If I was running a similar process in Excel this would take maybe 15-30 sec
Everything is in memory, I can't see (with my limited knowledge of javascript) why my code is so slow
Thanks
A Google sheet with data
//Sheet Name
//Values in Range to be overwritten by Header names
//List of Header names
//New Header Name 1
//New Header Name 2
function AsAboveSoBelow_Offers_Asks() {
AsAboveSoBelow('Elements',
["I can offer", "I have a ask"],
["Header1","Header2","Header3","Header4","Header5","Header6",
"Header7","Header8","Header9","Header10","Header11",
"Header12","Header13","Header14"],
"Offers",
"Asks");
}
function AsAboveSoBelow(shtName, arrPBV, arrHeaders, newHeader1, newHeader2) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName(shtName);
var LC = s.getLastColumn();
var r = s.getDataRange();
var v = r.getValues();
var start = new Date();
var temp ="";
//Dim A
var A = [];
for (var i = 0; i < v.length; i++) {
A[i] = [];
for (var j = 0; j <= arrPBV.length - 1; j++) {
A[i][j] = '';
}
}
for(var e = 0; e <= arrPBV.length - 1; e++) {
var search_Term = arrPBV[e];
for(var row = 0; row < v.length; row++) {
for(var col = 0; col <= arrHeaders.length - 1; col++) {
var col2 = HTN(shtName,arrHeaders[col])
var replace_Term = arrHeaders[col];
if(v[row][col2-1].toString().indexOf(search_Term) > -1) {
temp = temp + replace_Term + "|"
}
}
//remove trailing pipe
A[row][e] = temp.replace(/\|(?=\s*$)/, '')
temp = ""
}
}
A[0][0]= newHeader1
A[0][1]= newHeader2
s.getRange(1, v[0].length +1, v.length,A[0].length).setValues(A);
var end = new Date();
var executiontime = end - start;
Logger.log(executiontime);
};
//Helper function
function HTN(shtName,cheader){
var headers =
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName).getDataRange().getValues().shift();
var colindex = headers.indexOf(cheader);
return colindex+1;
}
You want to reduce the process cost of your script.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:
In your script, HTN() is used as the for loops. And the function includes SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName).getDataRange().getValues().shift();. In your script, the Spreadsheet and sheetName are not changed. So headers is always same. I thought that this might be the main modification point.
Modified script:
Please modify your script as follows.
function AsAboveSoBelow_Offers_Asks() {
AsAboveSoBelow(
'Elements',
["I can offer", "I have a ask"],
["Header1","Header2","Header3","Header4","Header5","Header6","Header7","Header8","Header9","Header10","Header11","Header12","Header13","Header14"],
"Offers",
"Asks"
);
}
function AsAboveSoBelow(shtName, arrPBV, arrHeaders, newHeader1, newHeader2) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName(shtName);
// var LC = s.getLastColumn(); // It seems that this is not used.
var r = s.getDataRange();
var v = r.getValues();
var start = new Date();
var temp ="";
//Dim A
var A = [];
for (var i = 0; i < v.length; i++) {
A[i] = [];
for (var j = 0; j <= arrPBV.length - 1; j++) {
A[i][j] = '';
}
}
var h = s.getRange(1, 1, 1, s.getLastColumn()).getValues()[0]; // Added
for(var e = 0; e <= arrPBV.length - 1; e++) {
var search_Term = arrPBV[e];
for(var row = 0; row < v.length; row++) {
for(var col = 0; col <= arrHeaders.length - 1; col++) {
var col2 = h.indexOf(arrHeaders[col]) + 1; // Modified
var replace_Term = arrHeaders[col];
if(v[row][col2-1].toString().indexOf(search_Term) > -1) {
temp = temp + replace_Term + "|"
}
}
//remove trailing pipe
A[row][e] = temp.replace(/\|(?=\s*$)/, '')
temp = ""
}
}
A[0][0]= newHeader1
A[0][1]= newHeader2
s.getRange(1, v[0].length +1, v.length,A[0].length).setValues(A);
var end = new Date();
var executiontime = end - start;
Logger.log(executiontime);
};
Note:
In my environment, the process time of the modified script was about 5 seconds.
If this was not the direct solution, I apologize.
I have a simple code to fill an array with some conditions but each time I get this error :
Uncaught TypeError: int_part is not a function
what's the problem here? what I'm missing?
here is the code:
var totalSlides = 4; // total number of slides we have
var lastSlideInt = 20; // numbers of review interactions on the last slide
var n = totalSlides - 1;
var x = lastSlideInt / (n * (n + 1) / 2);
var cal = [];
for (var i = 1; i < lastSlideInt; i++) {
cal.push(i * x);
}
var indexs = [];
var minus = [];
//
var sum = 0;
var floatSum = 0;
for (var i = 0; i < cal.length; i++) {
sum += cal[i];
if (sum >= 1) {
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
}
//
function int_part(y) {
return int_part = Math.trunc(y);
float_part = Number((y - int_part).toFixed(2));
}
function float_part(d) {
int_part = Math.trunc(d);
return float_part = Number((d - int_part).toFixed(2));
}
console.log(int_part(0.2));
I think the error should be somewhere on the if statement:
if (sum >= 1){
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
You are reassigning the functions int_part and float_part to number inside the body of function. You should only return the values.
var totalSlides = 4; // total number of slides we have
var lastSlideInt = 20; // numbers of review interactions on the last slide
var n = totalSlides - 1;
var x = lastSlideInt / (n*(n+1)/2);
var cal = [];
for (var i = 1; i < lastSlideInt; i++ ){
cal.push(i * x);
}
var indexs = [];
var minus = [];
//
var sum = 0;
var floatSum = 0;
for (var i = 0; i < cal.length; i++) {
sum += cal[i];
if (sum >= 1){
var pusher = int_part(sum) + int_part(floatSum);
floatSum += float_part(sum);
minus.push(pusher);
indexs.push(i);
}
}
//
function int_part(y){
return Math.trunc(y);
}
function float_part(d){
let int_part = Math.trunc(d);
return Number((d-int_part).toFixed(2));
}
console.log(int_part(0.2));
I'm working on a piece of code to turn text to binary. First, I turn the text to decimal, then the decimal to binary. The problem I'm getting, is in the 'decimalToBinary' function, it is telling me "Uncaught TypeError: Cannot read property 'toString' of undefined", could someone explain what's wrong?
function start() {
var text = readLine("Input the string you would like to encode: ");
var binary = textToBinary(text);
println(binary);
}
function textToBinary(text) {
var toASCII = [];
var toBINARY = [];
text.toUpperCase();
for (var i = 0; i < text.length; i++) {
var ASCII_CODE = text.charCodeAt(i);
toASCII.push(ASCII_CODE);
}
for (var j = 0; j < toASCII.length; i++) {
var arrnum = toASCII[i]
var final = decimalToBinary(arrnum);
toBINARY.push(final);
}
return toBINARY;
}
function decimalToBinary(decimalValue) {
var binaryBase = 2;
var numBitsDesired = 8;
var binaryValue = decimalValue.toString(binaryBase);
while (binaryValue.length < numBitsDesired) {
binaryValue = "0" + binaryValue;
}
return binaryValue;
}
You've some typos in your code:
function textToBinary(text){
var toASCII = [];
var toBINARY = [];
text.toUpperCase();
for(var i = 0 ; i < text.length ; i++){
var ASCII_CODE = text.charCodeAt(i);
toASCII.push(ASCII_CODE);
}
for(var j = 0 ; j < toASCII.length ; i++){ // <- This should be j++ instead of i++
var arrnum = toASCII[i] // <- Same here; j instead of i (i is off limits).
var final = decimalToBinary(arrnum);
toBINARY.push(final);
}
return toBINARY;
}
By accessing an array with an invalid index (out of bounds), you're getting an undefined value.
I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});