I need a counter which will count up numbers with different increase per tick depending on day of the week.
I found this counter: https://stackoverflow.com/a/3346311 which is counting the way I need but now I don't know how to make it to change INCREMENT value depending on day of the week.
Sorry for my poor english, hope question is understandable.
Regards
Thanks a lot Guys for all answers, I'm very impressed.
Date.getDay() returns the current day of the week starting at 0 (sunday)
var INCREMENT;
var dayOfWeek = new Date().getDay();
switch(dayOfWeek){
case 0: //Sunday
INCREMENT = 2; //Add your number
break;
case 1: //Monday
INCREMENT = 3; //Add your number
break;
//...
case 6: //Saturday
INCREMENT = 5; //Add your number
break;
}
Or you could do it like this
var daysToIncrementValues = {0: 5, 1:4, 2:3, 3:2, 4:1, 5:9, 6:7} // the values assigned are random here, you can assign whatever value
var todaysIncrementValue = dayToIncrement(new Date().getDay())
More concise, and no switch.
You should use setInterval() for this. And inside your function block, declare some conditionals, where you increment the count a different value depending on the day of the week.
To find the day of the week, use the new Date().getDay() method, which will return a number from 0 through 6, depending on the day.
var date = document.getElementById("date");
var count = 0;
setInterval(function() {
if (new Date().getDay() === 0) { // On Sunday's, increment by 1
count += 1;
}
else if (new Date().getDay() === 1) { // On Monday's, increment by 2
count += 2;
}
else if (new Date().getDay() === 2) { // On Tuesday's, increment by 3
count += 3;
}
else if (new Date().getDay() === 3) { // On Wednesday's, increment by 4
count += 4;
}
else if (new Date().getDay() === 4) {
count += 5;
}
else if (new Date().getDay() === 5) {
count += 6;
}
else {
count += 7;
}
date.innerHTML = count;
},1000);
Let me explain the above code.
I have an empty paragraph with an id equal to date and I'm referencing it through document.getElementById. I'm initializing a count variable to 0 upon page load.
At the end of my setInterval() loop, I'm adding the result of count to my div. The loop is being run once a second, which is represented by 1,000, which is the number of milliseconds the loop should be run. You can change this to whatever you like.
I just created a fiddle
http://jsfiddle.net/3nawhmdf/
If you want more DRY code, you could try something like this.
var date = document.getElementById("date");
var count = 0;
setInterval(function() {
count += (new Date().getDay() + 1);
date.innerHTML = count;
},1000);
Credit goes to bonesbrigade for this solution
Related
Here is my code but this array returns only the same elements, i am trying to create an array which contains 10 elements as the next mondays anyone know please help me
my code:
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() + +!!excludeToday +
(dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
return refDate;
}
let arr=[]
for(let i=0;i<10;i++){
arr.push(arr[i]=getNextDayOfTheWeek("Monday",false))
}
console.log(arr)
getNextDayOfWeek is being given the same inputs and so will have the same outputs.
You need to:
Establish the base line date and pass it as the third parameter
Pass the resulting date on the subsequent calls so that it advances
Indicate that it should exclude the base line date if it matches the requested date
Insert a new Date into the result array, because Dates are objects and thus passed by reference. If you don't do this, each call of getNextDayOfTheWeek will be making changes to the same object stored in each position of the result array.
Note that your local time might cause the displayed date to appear to be before or after the expected date. You will likely need to decide how to account for local timezone (note that the result might show Z at the end of the time indicating UTC).
let arr=[]
let refDate = new Date()
for(let i=0;i<10;i++){
refDate = getNextDayOfTheWeek("Monday",false, refDate)
arr.push(refDate)
}
function getNextDayOfTheWeek(dayName, excludeToday = true, refDate = new Date()) {
const dayOfWeek = ["sun","mon","tue","wed","thu","fri","sat"]
.indexOf(dayName.slice(0,3).toLowerCase());
if (dayOfWeek < 0) return;
refDate.setHours(0,0,0,0);
refDate.setDate(refDate.getDate() + +!!excludeToday +
(dayOfWeek + 7 - refDate.getDay() - +!!excludeToday) % 7);
return refDate;
}
let arr=[]
let refDate = new Date()
for(let i=0;i<10;i++){
refDate = getNextDayOfTheWeek("Monday", i > 0 ? true : false, refDate)
arr.push(new Date(refDate))
}
console.log(arr)
This is my first question on stack overflow although this question had been answered before I didn't get enough details to understand why the code was written that way and I didn't just want to copy and paste the solution without understanding it.
The snail climbs 7 feet each day and slips back 2 feet each night, How many days will it take the snail to get out of a well with the given depth?
Sample Input
31
Sample Output
6
this is was what i wrote but it didn't work
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
let climb = 0, days = 0;
for(climb + 7; climb < depth; days++){
climb += 2;
console.log(days);
try this:
var depth = parseInt(readline(), 10);
var day = 0;
for(let climb = 0; climb <= depth;) {
day +=1;
climb += 7;
if(climb >= depth) {
break;
}
climb -= 2;
}
console.log(day);
Just take input and write this
var day= Math.ceil((depth-2)/5);
and output that!
/* day --> 7++
night --> 2-- */
var day = 0;
var total = 0;
var input = 41;
while (input>total){
day++;
total+=7;
if (total>=input){
console.log(day);
break;
}
total = total -2
}
As mentioned in the comments, no need to loop. Just work out the math of the problem an use that.
function snailCalc (depth, dailyGain, nightlyLoss) {
var days = 1;
var netGain = dailyGain-nightlyLoss;
if(depth > dailyGain ) {
//Basic calc based on net gain taking the first day into account
days = (depth-dailyGain)/netGain;
//Add the fist day
days += 1;
//We want whole days so use Mathc.ceil
days = Math.ceil(days)
//Or we could do all that in one line
//days = Math.ceil(((depth-dailyGain)/netGain) + 1);
}
return days;
}
const gain = 7;
const loss = 2
for(var d = 1; d < 31; d++)
{
console.log(`Depth: ${d}, Days: ${snailCalc(d, gain, loss)}` )
}
Bob
function main() {
var depth = parseInt(readLine(), 10);
console.log(Math.round(depth / 5))
}
function main() {
var depth = parseInt(readLine(), 10);
//your code goes here
var days=1;
var level =0;
for(level =0;level<depth;days++){
level+=7
if(level<depth){
level-=2;
} else{
break ;
}
}console.log(days)
}
Try this, I had the same trouble a couple days ago and we find the error is that using js you need to reset the variable where you sum the result before evaluate again if the distance the snail climbed that day is greater than the depth to end the clycle.
depth = 31;
let days = 0;
let climb = 0;
while(climb < depth){
let result = climb + 7;
if(result >= depth){
days++;
break;
}
climb = result - 2;
days++;
//console.log("climb ",climb);
}
console.log(days);
You can change the function input and test the snipet:
for more you can run code and check result ↗
Eg : main(128) // 26
function main(input) {
let depth = input
let climbsUp = 7
let slipsBack = 2
let distance = climbsUp - slipsBack
let days = 0;
let rDepth = Math.round(depth / distance)
for (let i = 0; i < rDepth; i++) {
distance = distance + 5
days = ++days
if (days === 6) {
console.log('days will it take the snail to get out of a well : ' + rDepth)
} else {
console.log('days will it take the snail to get out of a well : ' + rDepth)
break;
}
}
}
main(42);
main(128);
I have written a code that raises a flag when number of leaves taken by a person exceeds 5 business days. However, it doesn't raise the flag when we have weekend in middle. Say, someone takes leave on 23,24 and then on 27,28 and 29. As 25 and 26 are weekends, tool doesn't count it. Can someone help me on how i must check the weekend dates here and push the value as "Yes" that includes weekend dates ?
function PrepareReport(reportData) {
var vacationData = [];
var dayValuesStr = '';
var dayValuesArray = [];
if ($("#ddlfromYear").val() == $("#ddltoYear").val()) {
count = parseInt($("#ddltoMonth").val()) - parseInt($("#ddlfromMonth").val());
}
else {
count = 12 - parseInt($("#ddlfromMonth").val()) + parseInt($("#ddltoMonth").val());
}
//val.ResourceID FullName EnterpriseID WorkOrder Domain Totalhours
vacationData.push(reportData.FullName);
vacationData.push(reportData.EnterpriseID);
vacationData.push(reportData.WorkOrder);
vacationData.push(reportData.Domain);
if (reportData.IsOffshore == 1) {
vacationData.push('Offshore');
}
else {
vacationData.push('Onshore');
}
vacationData.push(reportData.TOTALHOURS);
var counter = 0;
FlagCounterLastVal = 0;
vacationData.push("No");
for (var monthNum = 0; monthNum <= count; monthNum++) {
dayValuesStr = reportData['MONTH' + monthNum];
if (dayValuesStr) {
dayValuesArray = dayValuesStr.split(',');
var countArray = dayValuesArray.length - 1;
$.each(dayValuesArray, function (key, val) {
if (val.endsWith('.00'))//round off values
{
if (parseInt(val) == 0) {
vacationData.push('-');
counter = 0; // resetting counter to 0 for non-consecutive days
}
else {
if (FlagCounterLastVal > 0) {
counter = FlagCounterLastVal;
}
counter++;
vacationData.push(parseInt(val));
****if (counter >= 5 && FlagCounterLastVal == 0) {
var index = vacationData.indexOf("No");
vacationData[index] = "Yes";
}****
if (key == (countArray) && count > 0) { // vacation taken at the month ends
FlagCounterLastVal = counter;
}
}
}
else {
vacationData.push(val);
}
});
}
}
return vacationData;
}
You can use getDay for that.
var day = yourDateObject.getDay();
var isWeekend = (day === 6) || (day === 0);
6 = Saturday, 0 = Sunday
I won't be sharing code here as it's Data Structure and would like you to think a little bit, and try yourself first. If still you won't be able to code it then I will help you out in your code.
What I would do is have 2 arrays, both will be sorted this will help in search.
1. Having all weekends dates. // weekendArr
2. Leave dates taken by employee. //leaveArr
Steps
1. delete all the weekendArr dates from leaveArr.
2. Check if leaveArr have continues dates more then 5 or what ever you want it to be.
3. If it is greater then 5 then raise a flag for that employee.
Now you need to decide what data structure you will use to maintain employee leaves, employeeID, and leave flag.
Hope this will be enough to figure out code now.
I can't get my program to work. The problem is a kata from Codewars:
Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
Example:
persistence(39) === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) === 0 // because 4 is already a one-digit number
I've gone through answers to similar problems here already. This is my code:
var count = 0;
var product = 1;
function persistence(num) {
if (num.toString().length == 1) {
count+=0;
return count;
}
for (i of num.toString()) {
product *= Number(i);
}
count++;
var newProduct = product;
// reset product to 1 so that line ten does not
// start with the product from the last loop
product = 1;
persistence(newProduct);
}
I can't tell what the problem is. Initially I was getting a maximum call stack exceeded error. I researched that and realized I did this for my base case:
if (num.length == 1) {
count+=0;
return count;
}
instead of
if (num.toString().length == 1) {
count+=0;
return count;
}
My logic seems sound. What could the problem be?
Here's a much better way of solving your problem, complete with comments that I think gives a pretty clear explanation of what's going on.
function persistence(num) {
// Create a new function that you'll use inside your main function
function multiply(n) {
// Multiply the first number by next number in the array
// until the entire array has been iterated over
return n.reduce(function(a,b){return a*b;});
}
// Set the count to 0
var count =0;
// Use a while loop to iterate the same number of times
// as there are digits in num
while (num.toString().length > 1) {
// Splits the num into an array
num= num.toString().split("");
// Runs multiply on our num array and sets num to the returned
// value in preparation of the next loop.
// The multiply function will for 39 run 3 * 9 = 27,
// next iteration we've set num to 27 so multiply will be
// 2 * 7 = 14, then 1 * 4 = 4, and since num 4 now
// has a length <= 1 the loop stops.
num = multiply(num);
// Increase count by 1 each iteration, then run the next
// iteration in the loop with the new value for num being
// set to the result of the first multiplication.
count++;
}
return count; // return the value of count
}
console.log(persistence(39));// === 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
console.log(persistence(999));// === 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
console.log(persistence(4));// === 0 // because 4 is already a one-digit number
https://jsfiddle.net/8xmpnzng/
Use "of" instead of "in". "in" looks for properties. "of" increments an array.
var count = 0;
var product = 1;
function persistence(num) {
if (num.toString().length == 1) {
count+=0;
return count;
}
for (i of num.toString()) {
product *= Number(i);
}
count++;
var newProduct = product;
// reset product to 1 so that line ten does not
// start with the product from the last loop
product = 1;
persistence(newProduct);
}
I'm pretty sure it's this block:
for (i in num.toString()) {
product *= Number(i);
}
That's a for...in loop, which is used to iterate over keys in an object. If you want to multiply each digit of the num string together, you could split the string into an array, and use the reduce method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce):
//this coerces the number into a string
const numString = num + ''
//this is the function to pass as the first argument into the reduce method
const multiplyAll = (accumulator, currentVal) => accumulator * Number(currentVal)
let product = numString.split('').reduce(multiplyAll, 1)
It's generally best practice to avoid declaring global variables outside of a function's scope, but you can do a cool trick with your recursion where you declare your count as a parameter in your function like so:
function persistence(num, count = 0) {
And then when you call it again with recursion, you simply add 1 like so:
function persistence(product, count + 1) {
Simpler way of Persistence:
let countIteration = 1;
function persistence(num) {
let numStr = num.toString();
if(numStr.toString().length === 1) {
return 0;
}
let numArr = numStr.split("");
let persistRes = numArr.reduce((acc, curr) => acc = curr * acc);
if (persistRes.toString().length !== 1) {
countIteration += 1;
return persistence(persistRes);
}
else {
return countIteration;
}
}
console.log(persistence(39)); // === 3
console.log(persistence(15)); // === 1
console.log(persistence(999));// === 4
This is my array. Its length is about 9000. This is what a small bit of it looks like:
foreach_arr = ["21:07:01.535", "21:07:01.535", "21:07:26.113"]
There are a few occurences where the times diff is greater than a minute, and that is when I want to grab those times. And later use those times to get certain indices from another array. i.e "array"
I'm also using moment.js for time parsing.
Expected result: array = [8127, 9375, 13166, 14182]
Actual result: array = [8127, 13166]
Can't seem to find the issue here, I am getting 2 results when im supposed to be getting 4.
If the whole array is needed for troubleshooting, ill add it if I can.
var xx = foreach_arr.length - 1;
for(var z = 0; z < xx; z++) {
var current_row = foreach_arr[z];
var next_row = foreach_arr[z + 1];
var msElapsedTime = moment(next_row,"HH:mm:ss.SSS").diff(moment(current_row, "HH:mm:ss.SSS")) / 1000;
if(msElapsedTime > 60) {
attempt_indices.push(foreach_arr[z]);
}
}
for(var x = 0; x < attempt_indices.length; x++) {
array.push(newdata.indexOf(attempt_indices[x]));
}
Since the OP doesn't really need my code anymore, I'm posting it here to remove the downvote as much as anything else :)
const foreach_arr = ["21:07:01.535", "21:07:01.535", "21:07:26.113", '22:01:01.000'];
let processedForeach_arr = [];
let gtOneMinuteDiff = [];
foreach_arr.forEach((elem1, index1) => {
// elem1.split(':') turns foreach_arr[0] into ['21', '07', '01.535']
const splitElementArray = elem1.split(':');
let timeInMs = 0;
// this changes ['21', '07', '01.535'] into [75600000, 420000, 1535]
splitElementArray.forEach((elem2, index2) => {
if (index2 === 0) { // elem2 is hours. 3.6M ms per hour.
timeInMs += parseFloat(elem2) * 60 * 60 * 1000;
} else if (index2 === 1) { // elem2 is minutes. 60K ms per minute.
timeInMs += parseFloat(elem2) * 60 * 1000;
} else if (index2 === 2) { // elem2 is seconds. 1K ms per second.
timeInMs += parseFloat(elem2) * 1000;
} else {
throw `Expected array element formatted like HH:MM:SS.ms. Error on
element ${elem1}.`;
}
});
processedForeach_arr.push(timeInMs);
let timeDiff = processedForeach_arr[index1 - 1] - processedForeach_arr[index1];
if (Math.abs(timeDiff) > 60000) {
gtOneMinuteDiff.push(timeDiff);
}
});
To get the difference in milliseconds between foreach_arr[n] and foreach_arr[n+1], this code will
split each element of foreach_arr into 3 strings (hours, minutes, and seconds + milliseconds)
run parseFloat on each of those values to convert them to a number
convert all numbers to milliseconds and add them together
compare each consecutive value and return the difference.
Ok, I got this far and my son needs me. I'll finish out the code asap but you might beat me to it, hopefully the instructions above help.
turns out my code wasn't wrong. Just my idea of the whole proccess.
array = [8127, 13166]
is what I initialy get. With this, I use indexOf on my other array to eventually get my array as expected:
var another_test_arr = [];
for(var v = 0; v < array.length ; v++) {
var find = foreach_arr.indexOf(attempt_indices[v]);
another_test_arr.push(array[v], newdata.indexOf(foreach_arr[find + 1]));
}
Result: array = [8127, 9375, 13166, 14182]