How to programmatically identify where n would fit in this sequence? - javascript

I have a number I want to conform to the closest value in the following sequence:
2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42...
If 10 is passed, it would become 12, 13 would become 15, 17 would become 19.
How would I approach this in a function?

If you don't know whether the array is sorted, you could use code like this to find the value in the array that is the closest to the passed in value (higher or lower):
var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42];
function findClosestValue(n, list) {
var delta, index, test;
for (var i = 0, len = list.length; i < len; i++) {
test = Math.abs(list[i] - n);
if ((delta === undefined) || (test < delta)) {
delta = test;
index = i;
}
}
return(list[index]);
}
If you want the closest number without going over and the array is sorted, you can use this code:
var list = [2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42];
function findClosestValue(n, list) {
var delta, index;
for (var i = 0, len = list.length; i < len; i++) {
delta = n - list[i];
if (delta < 0) {
return(index ? list[index] : undefined);
}
index = i;
}
return(list[index]);
}

Here is a jsFiddle with a solution that works for an infinite series of the combination "+3+4+3+3+4+3+3+4+3+3+4....." which seems to be your series. http://jsfiddle.net/9Gu9P/1/ Hope this helps!
UPDATE:
After looking at your answer I noticed you say you want the closes number in the sequence but your examples all go to the next number in the sequence whether it is closest or not compared the the previous number so here is another jsfiddle that works with that in mind so you can choose which one you want :).
http://jsfiddle.net/9Gu9P/2/

function nextInSequence(x){
//sequence=2, 5, 9, 12, 15, 19, 22, 25, 29, 32, 35, 39, 42
var i= x%10;
switch(i){
case 2:case 5:case 9: return x;
case 0:case 1: return x+ 2-i;
case 3:case 4: return x+5-i;
default: return x+9-i;
}
}
alert(nextInSequence(10))

Related

How do I iterate though an array and do actions based on conditions?

My goal is the following:
Create a loop that compares the array of numbers provided, for the number 28.
Log over, if it is greater than 28, and under if it is less than 28.
Don't log anything if it is equal to 28.
Expected output:
2 is under
40 is over
31 is over
This is my code currently; I feel like I am so close, but I'm not sure.
var rando_array = [2, 40, 31, 29, 9, 12, 41, 90];
rando_array.sort();
for (var i = 0; i < var rando_array.length; i++) {
var Its;
if (i > 28) {
Its = "over";
} else if (i < 28) {
Its = "under";
}
console.log(rando_array[i] + "Its");
};
Since you wanted to loop though the array, this solution uses a for-loop.
The same result could be achieved using forEach , maps etc...
let rando_array = [2, 40, 31, 29, 9, 12, 41, 90];
for (var i = 0; i < rando_array.length; i++) {
if (rando_array[i] > 28) {
console.log(rando_array[i] + " is over")
} else if (rando_array[i] === 28) {
// Do nothing
/* Uncomment to log eqaul
console.log(rando_array[i] + " is equal")
*/
} else {
console.log(rando_array[i] + " is under")
}
};
let arr = [2, 40, 31, 29, 9, 12, 41, 90]
const max_value = 28
arr.filter(item => item > max_value).forEach(number => {
// console logs if num is greater than 28
console.log(number)
})

JavaScript split array in half juxtapose the first half with second half

What is the method to evenly split an array into two. Then, position the second half underneath the first all for the purpose of comparing whether or not a new final array should receive a zero or one in the slots.
var master_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];
var first_half = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
var second_half = [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38];
var final_usable_array_reduced = [];
So, given a form with 38 check boxes, if the 5th, 19th, 37th, and 38th check boxes were checked, the final_usable_array_reduced would be
final_usable_array_reduced = [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1];
final_usable_array_reduced[4] = **represents the 5th <strong>or</strong> 24th box being checked**
final_usable_array_reduced[18] = **represents the 19th <strong>or</strong> 38th boxes being checked**
I think you can implement this with a simple for loop over half the master_array, oring the values in the bottom half of the array with those in the top half:
var master_array = new Array(38).fill(0);
master_array[4] = 1;
master_array[18] = 1;
master_array[36] = 1;
master_array[37] = 1;
let len = master_array.length / 2;
final_usable_array_reduced = new Array(len);
for (let i = 0; i < len; i++) {
final_usable_array_reduced[i] = master_array[i] | master_array[i + len];
}
console.log(final_usable_array_reduced);
Check this one:
var array = [0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0];
var firstHalf = array.slice(0,array.length/2);
var secondHalf = array.slice(array.length/2);
var result = firstHalf.map(function(e,i){
return e || secondHalf[i];
});
console.log(result);
What I'm doing here is spliting the array into two halfs with slice (considering that the array elements are even, of course), and after that I map the first one returning 1 (or true, is the same) if firstArray[i] or secondArray[1] is 1.
Consider the following.
$(function() {
function addChecks(count, tObj, cont) {
var i;
if (cont == undefined) {
i = 0;
} else {
i = parseInt($("input:last").val()) - 1;
count = i + count;
}
for (i; i <= count; i++) {
$("<input>", {
type: "checkbox",
value: (i + 1),
title: (i + 1)
}).appendTo(tObj);
}
}
function checksToArray() {
var arr = [];
$("input[type='checkbox']").each(function() {
arr.push($(this).prop("checked"));
});
return arr;
}
function compHalfArr(a) {
var arr = [];
var h = Math.floor(a.length / 2);
for (var i = 0; i <= h; i++) {
arr.push(a[i] || a[(i + h)]);
}
return arr;
}
addChecks(14, $(".section-1"));
addChecks(14, $(".section-2"), true);
$("button").click(function() {
var allChecks = checksToArray();
var compChecks = compHalfArr(allChecks);
$(".results").html("<span>" + compChecks.join("</span><span>") + "</span>").find("span:last").remove();
});
});
.checks input {
margin-right: 20px;
}
.results span {
display: inline-block;
font-family: Arial, sans-serif;
width: 40px;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="checks section-1"></div>
<div class="checks section-2"></div>
<button>Check</button>
<div class="results"></div>
You can do a loop using a halfway marker.

Counting iterations of 1 in an array

My goal is to count iterations of 1 in an array.
I have this code:
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] === 1)
count++;
}
console.log(count);
Right now, it logs 5, but including "10" it should log 6, since "10" also contains a 1. What code can I use for this?
What about:
var count = array.toString().split('1').length - 1;
You can use filter method in combination with length property in order to write a more cleaner solution.
Also, use join and split methods in order to achieve your requirement.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
console.log(array.join('').split('').filter(a=>a==1).length);
or using reduce method.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
console.log(array.join('').split('').reduce((c,i)=> i==1 ? c+1 :c).length);
Just convert every item to string, and then check if 1 belongs to that number or not.
So for number 10, the string is '10' and then '10'.indexOf('1') equals to 0. So every time 1 is found within the string, you increment the counter.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for (var i = 0; i < array.length; ++i) {
if (array[i].toString().indexOf('1') >= 0)
count++;
}
console.log(count);
You need to split your numbers into digits and iterate over each digit (which is a character) and compare with it. Use Object#toString to parse the number into the string, split into characters by String#split and using Array#forEach iterate over characters and do the same comparison there.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i) {
var numberAsString = array[i].toString();
numberAsString.split('').forEach(char => {
if(char === '1') {
count++
}
});
}
console.log(count);
You'll need to convert each number to a string and use indexOf
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = array.reduce(function(p,c){
if(c.toString().indexOf("1")>-1)
p++;
return p;
},0);
console.log(count);
You can Array#join the array items to a string and count using String#match with a regular expression:
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
// the || [] is a fallback in case there is no 1, and match returns null
var result = (array.join('').match(/1/g) || []).length;
console.log(result);
You could check every character of the joined string.
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1],
count = 0,
i,
temp = array.join('');
for (i = 0; i < temp.length; ++i) {
if (temp[i] === '1') {
count++;
}
}
console.log(count);
var array = [10, 3, 22, 40, 1, 40, 1, 22, 1, 0, 3, 53, 1, 1];
var count = 0;
for(var i = 0; i < array.length; ++i){
if( array[i] === 1 || array[i].toString().includes("1") )
count++;
}
console.log( count );

Get numbers greater than n

I need to console.log every number that is greater than 10 from this row
[ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6]
I know it should be something like this
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
for (var i = 0; i<row; i++)
{
console.log(niz[i]);
}
Well you could either use a for loop or mapping. For loop would be like this:
for (var i = 0; i<row.length; i++)
{
if (row[i] > 10)
console.log(row[i]);
}
To use mapping:
row.map(function(element){
if (element > 10)
console.log(element);
});
As you stated in the question, you need to use a for-loop to iterate trough all the items in your array. This is almost done correctly, but instead of doing i<row, you need to check against the length of the row (row.length).
In your case, i will be the index in your list, and it will increment with one (i++) in each iteration in the for-loop until you reach the number of items in rows.
The thing that you are missing is a if-statement to check if the item in the array is greater than 10.
I've tried to explain each line with a comment.
var row = [10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
var items = row.length; // number of items in your array
for (var i = 0; i < items; i++) { // iterate trough all the items
var numberInRow = row[i]; // the number with index number i in rows
var isGreaterThanTen = numberInRow > 10; // true if the number is greater than ten
if (isGreaterThanTen) { // will execute if isGreaterThanTen is true
console.log(numberInRow); // print number greater than 10 to console.
}
}
A forEach-loop seems a nice way of solving your problem:
var row = [ 10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6];
row.forEach(function(x){if(x>10){console.log(x)}})
or even shorter
[10, 10, 11, 12, 156, 9, 3, 5, 1, 61, 89, 5, 6].forEach(function(x){if(x>10){console.log(x)}})
The output in both cases:
11
12
156
61
89

Find all unique values that are sums of sub-arrays of an array of numbers... simple?

Sup fellow geeks!
I'm trying to make an array that lists all the possible values of the sums of the elements of an array. I'm sure this must be quite easy but I'm up to 2 or 3 hours now and I'm getting frustrated, I think I'm almost there...
var frootVals = [0,1,2,3,4,5]
var frootInc = frootVals
var fruitEnd = frootInc[frootInc.length-1]//begins at 5
var fruitAll = 15 // The total of all the numbers in the array. (this is actually
// calculated in another function, but lets just say I declared it as 15)
for (e = frootVals.length-2 ;fruitEnd !== fruitAll;e--){ //so I want it to
//finish when the final array entry is 15.
for (p = 1;p < e; p++){
var incEnd = frootInc[frootInc.length-p]
frootInc.push(incEnd + frootVals[p]) //1st time round (5 + 1 = 6, 5 + 2 = 7,
//5 + 3 =8, 5 + 4 = 9) THEN start again with 9 now being incEnd so pushes
//9+1 = 10 etc etc until the last digit is 15 and the whole loop stops...
}
}
EDIT - Basically the final result I'm after is frootInc to be be an array of the integers [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] - I'm sure I'll kick myself for giving up but I've only been learning a few weeks so this is all quite brain taxing.
After thinking about your question a bit, I think the easiest solution would be with recursion when the condition that the final value added to the array is less than the sum of values.
Here's a JS Fiddle for demo: http://jsfiddle.net/ukgzwpky/
To break it down a bit (and so that you may confirm I have the question right :D), say we have the following array:
[0, 1, 2, 3, 10, 15, 30]
The sum of the values are: 61. So the expected output array would be:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
To further break it down, the looping logic would do something like this:
// Get final value to add to previous values
var val = [0, 1, 2, 3, 10, 15, 30].pop();
// Add the final value - 30 - to all previous values (ignoring the zero)
.. loop here and push the values to our array ...
// For the first iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45]
// New values calculated from: 30 + 1, 30 + 2, 30 + 3, 30 + 10, 30 + 15
At this point, our max value of 61 is less than the final value of 45 So, we do it again!
var val = [0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45].pop();
.. loop here and push the values to our array ...
// Second iteration, the updated array looks like:
[0, 1, 2, 3, 10, 15, 30, 31, 32, 33, 40, 45, 46, 47, 48, 55, 60, 61]
// New values are: 45 + 1, 45 + 2, 45 + 3, 45 + 10, 45 + 15
// Note that 45 + 30 would be greater than our sum of 61, so we break
If that's correct, here's a script that I wrote that populates such an array:
function getPopulatedArray(arr) {
var max = arguments[1] || getSum(arr),
current = arr.pop(),
temp = [],
i = 1,
len = arr.length;
// Populate temp array with values
for (; i < len; i++) {
if ((arr[i] + current) < max) {
temp.push(arr[i] + current);
} else {
temp.push(max);
break;
}
}
arr.push(current);
arr = arr.concat(temp);
// Done? Or should we continue?
if (arr[arr.length - 1] < max) {
return getPopulatedArray(arr, max);
} else {
return arr;
}
}
Again, the JS fiddle for demonstration: http://jsfiddle.net/ukgzwpky/
Hopefully this helps!
A very simple solution would be to do something like this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){ // Iterate over the array twice
for (var j = 0; j < frootVals.length; j++){ // To calculate all combinations
result.push(frootVals[i] + frootVals[j]);
}
}
Now, if you don't want duplicates, try this:
var frootVals = [0,1,2,3,4,5]
var result = [];
for (var i = 0; i < frootVals.length; i++){
for (var j = 0; j < frootVals.length; j++){
var value = frootVals[i] + frootVals[j];
if(result.indexOf(value) === -1){
result.push(value);
}
}
}
You could then use result = result.sort() if you want to output a sorted result.

Categories