I am working on solving an algorithm (do not want to explain my approach, as I am still trying to solve it on my own). However I am having difficulty with a particular part.
function smallestCommons(arr)
{
var rangeArray = [];
var outterArray = [];
var testArray = [];
arr = arr.sort(function(a,b){return a>b});
for(var i=arr[0];i<=arr[1];i++)
{
rangeArray.push(i);
}
for(var j=0;j<rangeArray.length;j++)
{
for(var k=1;k<=100;k++)
{
if(k%rangeArray[j] === 0)
{
outterArray.push([k]);
}
}
}
console.log(outterArray);
}
smallestCommons([1,5]);
The second part of the code I am looping through the items in rangeArray [1,2,3,4,5] and trying to insert all the multiples (from 1 to 100) of EACH index into a DIFFERENT array. But my code currently is pushing EACH individual number which is a multiple into its own array per each digit. I need it to push all the multiples of each index of rangeArray into outer array. So that I end up with a 2D array of all the multiples of rangeArray in different array for every iteration of j.
So for example instead of ending up with
outerArray == [[1],[2],[3]...]
I would end up with all the multiples of 1 (up to 100) into one array and then all the multiples of 2 into another array and so on and so forth so it looks like this.
outerArray == [[1,2,3,4...] [2,4,6,8...] [3,6,9,12...]]
Its very hard to explain, hopefully I have been clear. Thanks.
It's quite impossible to understand your question, but wisely you've described the output you're trying to generate...
Turns out, that's quite simple:
let arr = [];
for(let i = 1; i <= 100; i++) {
let innerArr = [];
for(let j = i; j <= 100; j += i) {
innerArr.push(j);
}
arr.push(innerArr);
}
console.log(arr);
how many elements should be in each multiple array? I guessed 100 but you can adjust that accordingly...
function smallestCommons(arr)
{
var rangeArray = [];
var outterArray = [];
var testArray = [];
arr = arr.sort(function(a,b){return a>b});
for(var i=arr[0];i<=arr[1];i++)
{
rangeArray.push(i);
}
for(var j=0;j<rangeArray.length;j++)
{
for(var k=1;k<=100;k++)
{
if(k%rangeArray[j] === 0)
{
var multipleArray = [];
for(var z=1;z<100;z++) {
multipleArray.push(z*k);
}
outterArray.push(multipleArray);
}
}
}
console.log(outterArray);
}
smallestCommons([1,5]);
Related
Let's say that I'm doing this because of my homework. I would like to develop some kind of schedule for the week to come (array of 6-7 elements - output result). But I have one problem. I need to figure it out how one element be positioned in the array and also his frequency must be exactly what user input is. Elements must be positioned at different index in the array.
I'm having that kind of input from user (just an example);
var arrayOfElements = ["el1","el2","el3"];
var el1Frequency = 3;
var el2Frequency = 2;
var el3Frequency = 1;
//output array of schedule (this is just an example)
var finaloutPutArray = ["el1","el2","el3","el1","el2","el1"];
Index of elements el1 is 0, 3 and 5, basically, I don't want elements to be repeated like this;
["el1","el1","el2","el3"...];
["el2","el1","el1","el3"];
Can you please give me some ideas on how to solve this problem.
I started like this;
var finalSchedule = [];
var totalDaysPerWeek = 6;
for(var i =0; i < totalDaysPerWeek; i++) {
...
}
This is one pattern, check my working snippet:
var arrayOfElements = ["el1","el2","el3"];
var obj = { el1: 3,
el2: 2,
el3: 1};
// First determine the max recurring of an element, this will be the number of cycles fo your loop
// Check key values
var arr = Object.keys(obj).map(function ( key ) { return obj[key]; });
// Get max value
var max = Math.max.apply( null, arr );
var finalArray = [];
// Iterate from 0 to max val
for(i = 0; i < max; i += 1){
// Iterate on array of elements
for(k = 0; k < arrayOfElements.length; k += 1) {
// If config of recurring
if( obj[arrayOfElements[k]] >= i+1 ) {
// Push into array
finalArray.push(arrayOfElements[k]);
}
}
}
console.log(finalArray);
I am trying to push numbers in an array into another array in groups of two.
If I have an array [1,4,3,2]; it should return [[1,4],[3,2]];
var arrayPairSum = function(nums) {
var len = nums.length / 2;
var arr = [];
for(var i = 0; i < len; i ++) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
can anyone see what I need to do to achieve this? I cannot figure it out.
You can use reduce method to achieve this. reduce method accepts a callback method provided on every item in the array.
In the other words, this method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
var array=[1,4,3,2,8];
var contor=array.reduce(function(contor,item,i){
if(i%2==0)
contor.push([array[i],array[i+1]].filter(Boolean));
return contor;
},[]);
console.log(contor);
If you really want to iterate over the array, may skip every second index, so i+=2 ( as satpal already pointed out) :
var arrayPairSum = function(nums) {
var len = nums.length - 1;//if nums.length is not even, it would crash as youre doing nums[i+1], so thats why -1
var arr = [];
for (var i = 0; i < len; i += 2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1, 4, 3, 2]);
The upper one crops away every non pair at the end. If you want a single [value] at the end, may go with
len=nums.length
And check later before pushing
if(i+1<nums.length) newArr.push(nums[i+1]);
You were pretty close. Simply change the length to nums.length and in the loop increment i by 2.
var arrayPairSum = function(nums) {
var len = nums.length - 1;
var arr = [];
for(var i = 0; i < len; i+=2) {
var newArr = [];
newArr.push(nums[i]);
newArr.push(nums[i + 1]);
arr.push(newArr);
}
console.log(arr); //this should give me [[1,4],[3,2]];
};
arrayPairSum([1,4,3,2]);
Given an array and a length, I want to derive every possible combination of elements (non-repeating) at the specific length.
So given an array of:
arr = ['a','b','c','d']
and a length of 3, I'm after a function that outputs a 2-dimensional array as follows:
result = [
['a','b','c'],
['b','c','a'],
['c','a','b'],
. . . etc.
]
I've tried tackling this and have had a deal of difficulty.
The following code uses a brute-force approach. It generates every permutation of every combination of the desired length. Permutations are checked against a dictionary to avoid repeating them in the result.
function makePermutations(data, length) {
var current = new Array(length), used = new Array(length),
seen = {}, result = [];
function permute(pos) {
if (pos == length) { // Do we have a complete combination?
if (!seen[current]) { // Check whether we've seen it before.
seen[current] = true; // If not, save it.
result.push(current.slice());
}
return;
}
for (var i = 0; i < data.length; ++i) {
if (!used[i]) { // Have we used this element before?
used[i] = true; // If not, insert it and recurse.
current[pos] = data[i];
permute(pos+1);
used[i] = false; // Reset after the recursive call.
}
}
}
permute(0);
return result;
}
var permutations = makePermutations(['a', 'a', 'b', 'b'], 3);
for (var i = 0; i < permutations.length; ++i) {
document.write('['+permutations[i].join(', ')+']<br />');
}
I'm having some trouble combining arrays into one array and then flipping it with the code below. The goal is to set an array of values in one column of a spreadsheet. After the titleArray function, I would like to have an array spread across multiple columns on one row. Then, using a function I found in another Stack Overflow thread (Google Spreadsheet Script - How to Transpose / Rotate Multi-dimensional Array?), I want to flip the array so it is spread across multiple rows on one column. The current code is returning an array for each element in array1 all inside of another array. Then, the transposeArray function is combining values from each array, 1 with 1, 2 with 2, and so on. Can anyone spot what I'm doing wrong here?
var titleArray = function(){
var output = [];
for(i=0; i < array1.length; i++){
if(array1[i].length > 0){
var titles = ["",array1[i] + " Data"].concat(array2, array3, array4, array5, array6, array7);
output.push(titles);
}
}
return(output);
}
}
function transposeArray(array){
var result = [];
for (var col = 0; col < array[0].length; col++) { // Loop over array cols
result[col] = [];
for (var row = 0; row < array.length; row++) { // Loop over array rows
result[col][row] = array[row][col]; // Rotate
}
}
return result;
}
transposeArray(titleArray);
I was able to sit down with a programmer and he helped me through this. Essentially, I needed to use the concat method instead of the push method. I tried using concat early in this process but was using it in the first way demonstrated below instead of the second. I've included the full new code below as well.
output.concat(titles);
output = output.concat(titles);
var titleArray = function(){
var output = [];
for(i=0; i < array1.length; i++){
if(array1[i].length > 0){
var titles = ["",array1[i] + " Data"].concat(array2, array3, array4, array5, array6, array7);
ouput = output.concat(titles);
}
}
return(output);
}
}
function transposeArray(array){
var result = [];
for (var col = 0; col < array[0].length; col++) { // Loop over array cols
result[col] = [];
for (var row = 0; row < array.length; row++) { // Loop over array rows
result[col][row] = array[row][col]; // Rotate
}
}
return result;
}
transposeArray([titleArray]);
What I want to do:
Search through a multi-dimensional array using multiple search strings.
Example of what I am currently doing:
var multiArray = [['Apples and pears', 'tuna salad'],['bananas tuna'],['the colour blue']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match) {
for (var i in singleArray) {
if (singleArray[i].indexOf(to_match)!= -1)
match_array.push(singleArray[i]);
}
return (match_array.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match('tuna');
find_match('the');
alert(match_array);
JSFiddle Demo
Questions:
Obviously this is a cluttered way of doing this. How can this be
streamlined(i.e. searching the multiArray directly and not using
multiple find_match functions)?
How can I get only the exact string matches, preferably without breaking up the multi-dimensional array?
What are your thoughts about searching through massive
multidimensional arrays?
Do you want something like this?
var multiArray = [['Foo', 'Bar'],['Foo'],['Bar']];
var singleArray = [];
var match_array = [];
// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
for (var x = 0; x < multiArray[i].length; x++) {
singleArray.push(multiArray[i][x]);
}
}
// Create a new array from matched strings
function find_match(to_match, where_search) {
for (var j in where_search) {
if(where_search[j] instanceof Array){
find_match(to_match, where_search[j]);
}else{
for (var i in to_match) {
if (where_search[j].indexOf(to_match[i]) ==0 &&
where_search[j].length == to_match[i].length)
match_array.push(where_search[j]);
}
}
}
return (where_search.length === 0 ? null : match_array);
}
// Find matching terms for match_array
find_match(['Foo', 'Bar'],multiArray);
alert(match_array);