I need to split a number to number of sections
I want number of sections, between each consecutive numbers in each section the number of the sections
For example
If the given number is 20 and the number of sections is 3
then need to split numbers 1 to 20 into three sections.
So the result will be
section 1 = [1,4,7,10,13,16,19] // between any
section 2 = [2,5,8,11,14,17,20]
section 3 = [3,6,9,12,15,18]
I'm using javascript to do this.... any idea
Sorry for my bad English
You could use two nested for loops and count the sections and the value to max.
function getSection(sections, max) {
var value, result = [], i;
for (i = 1; i <= sections; i++) {
result.push([]);
for (value = i; value <= max; value += sections) {
result[i - 1].push(value);
}
}
return result;
}
console.log(getSection(3, 20));
Something like that:
function get_s(s_cnt, w_num) {
var a = new Array(s_cnt), b = Math.ceil(w_num/s_cnt), c = w_num;
for (var i=0; i<s_cnt; i++) {
var b_ = (b < c) ? b : c; c -= b;
a[i] = new Array(b_);
for (var j=0; j<b_; j++) {
a[i][j] = j*s_cnt + i + 1;
}
}
return a;
}
var s = get_s(3,20);
for (var i=0; i<3; i++) console.log("section "+(i+1)+": "+s[i].join(", "));
Related
I have to create a Javascript program for a Fibonacci series, and following are the conditions:
Every number should be separated by a comma.
Method should check for valid values and return -1 (number) for integers less than 1, non numeric values.
Returned value should always be string for valid input passed.
Output string should end with a comma.
I have done the first 3 steps but stuck in the last one. Unable to understand that how can I add comma at the end of the series. Because if I define sum+= sum + ',', then the first time 11,2,3 is printed with no comma between the first 2 numbers.
function fibonacci(len) {
var a = 0,
b = 1,
f = 1,
sum = 1;
if (len > 2) {
for (var i = 2; i <= len; i++) {
f = a + b;
sum += ',' + f;
a = b;
b = f;
}
} else if (len == 1) {
sum = '1,1,';
} else {
sum = '-1';
}
return sum;
}
console.log(fibonacci(10))
function fibonacci(len) {
// check if valid length
if(isNaN(len) || (parseInt(len) | 0) !== len || len < 1) {
return -1;
}
// initialize starting value
var sequences = [1, 1];
var current = 1;
for(let i = 1; i<len; i++) {
// sum last 2 sequence
var x = sequences[i] + sequences[i-1];
sequences.push(x);
}
// join with comma
return sequences.join(", ") + ",";
}
console.log(fibonacci(1))
console.log(fibonacci(5))
console.log(fibonacci("a"))
Short answer: return sum+",";
I suggest you use an array and join. Also get rid of duff data at the start
Also loop from 1
function fibonacci(len) {
if (isNaN(len) || len < 1 ) return -1;
let a = 0, b = 1, f = 1, sum = [1];
for (let i = 1; i <= len; i++) {
f = a + b;
sum.push(f);
a = b;
b = f;
}
return sum === -1 ? sum : sum.join(",") + ",";
}
// tests
console.log(fibonacci(10))
console.log(fibonacci(1))
console.log(fibonacci(2))
console.log(fibonacci(0))
console.log(fibonacci("A"))
console.log(fibonacci(" 1 "))
I am working through this Free Code Camp exercise.
Return the sum of all odd Fibonacci numbers up to and including the
passed number if it is a Fibonacci number. The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and
8, and each subsequent number is the sum of the previous two numbers.
And here is what I have so far...
Any suggestions?
function sumFibs(num) {
var arr, isFibVal, isEvenVal, sum, i = 0, fibonacci = function (num){
var a, b, result, fibArr = [1];
a=0;
b=1;
result=b;
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
return fibArr;
},
isFib = function (val){
var prev = 0;
var curr = 1;
while(prev<=val){
if(prev == val){
return true;
} else {
return false;
}
curr = prev + curr;
prev = curr - prev;
}
},
isEven = function(someNumber){
return (someNumber % 2 === 0) ? true : false;
};
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
return sum;
}
All I get back is undefined which seems to be weird because i thought this part of my code was pretty cool—using the function values to check vs. in the if statement.
arr = fibonacci(num);
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
}
I won't give you the answer outright since you're going through FCC, but I'll provide you with some hints as to where to look:
See this segment:
for(var j = 0; j < num; j++){
result = a + b;
a = b;
b = result;
fibArr.push(result);
}
And this one:
function sumArray(array) {
for (
var
index = 0, // The iterator
length = array.length, // Cache the array length
sum = 0; // The total amount
index < length; // The "for"-loop condition
sum += array[index++] // Add number on each iteration
);
return sum;
}
Also, you probably don't need this segment at all:
isFibVal = isFib(num);
isEvenVal = isEven(num);
if (isFibVal && !isEvenVal){
sum += sumArray(arr);
Good luck. As someone who has finished a good chunk of the curriculum, I can say that Free Code Camp is the real deal.
You're pretty close and the other answer is good for pushing you in the right direction, I'll post a different way that does this using native JS functions:
Example of the code below in JSBin
function fibs(n) {
var f = [0, 1];
var extraNumber = 0;
for (var i = 0; i < n; i++) {
f.push(f[f.length - 1] + f[f.length - 2]);
}
// lets check if the passed in number is a fib:
if (f.indexOf(n) > -1) {
extraNumber = n;
}
console.log(f); // just to check we can cut all the logs later...
var filtered = f.filter(function(num) {
// filter out the even numbers
return num % 2 === 1;
});
console.log(filtered);
var sum = filtered.reduce(function(a, b) {
// add up whats left
return a + b;
});
console.log(sum);
return sum + extraNumber;
}
heres my solution, and i find it to be pretty readable:
function sumOddFibs(num) {
// initialize with 2 because
// fib sequence starts with 1 and 1
var sum = 2;
var prev = 1;
var curr = 1;
var next = 2;
while (next <= num) {
prev = curr;
curr = next;
next = prev + curr;
if (curr % 2 !== 0) {
sum += curr;
}
}
return sum;
}
You could start by defining variables for the previous number, current number, and total Fibonacci
To check for odd numbers, you could use an if statement and use %:
if (currNum % 2 !== 0){ }
If current number is odd, then you add it to the total
fibTotal += currNumber;
To determine the next Fibonacci number you, you will need to add the previous and current number:
var nextNumber = prevNumber + currNumber;
You will need to update the previous number to the current one
prevNumber = currNumber;
Set the current number to the next Fibonacci number in the sequence
currNumber = nextNumber;
Hope this helps.
How can I find the number of multiple for N numbers(as an array input) for a range 1 to K, where 1 < K < 10⁸ and 3 ≤ N < 25.
function findNumberOfMultiples(inputArray, maxSize) {
var count = 0;
var tempArray = [];
for (var i=0; i<maxSize; i++){
tempArray[i] = 0;
}
for (var j=0; j<inputArray.length; j++) {
for (var i=1; i<=maxSize; i++) {
if (i % inputArray[j]) {
tempArray[i-1] = 1;
}
}
}
for (var i=0; i<maxSize; i++) {
if (tempArray[i]==1) {
count++;
}
}
return count;
}
The above program fails for large number K. For example, if inputArray = [2,3,4] and maxSize(k) is 5,
Multiple of 2 is 2,4
Multiple of 3 is 3
multiple of 4 is 4
so total number of mutiple of 2 or 3 or 4 is 3 in range 1 to 5
You can solve this in O(N^2) where N is the number of elements in your array.
let us say you have two element in your array [a1,a2] and the range is K
your answer will be = >
K/a1 + K/a2 - K/lcm(a1,a2) // because you added them in both a1 and a2
So If you have a1,.....ax elements, your answer would be
K/a1+.....K/ax - K/lcm(ai,aj) (you have to replace i,j by (n*n-1)/2 combinations.
You will have to do K/lcm(ai,aj) O(N^2) times ((n*n-1)/2 time to be precise). So the algorithm complexity will be O(N^2) (There will be a Log(min(ai,aj)) factor but that would not make much difference to the overall complexity).
This will work any K as it only depends on your innput array size.
public int combinations(int K, int[] input){
int total = 0;
for(int i=0;i<input.length;i++){
total = total + Math.floor(K/input[i]);
}
for(int i=0;i<input.length;i++){
for(int j=i+1;j<input.length;j++){
if(i!=j){
int lcm =lcmFind(input[i], input[j]);
total = total - Math.floor(K/lcm);
}
}
}
return total;
}
The test case you have provided:
This function seems to do the trick :
var findMultiplesLength = function(arrayInput, max) {
var globalMultiples = [];
for (var j = 0; j < arrayInput.length; j++) {
var x = arrayInput[j];
var n = max / x;
for (var i=1; i < n; i++) {
mult = i * x;
if (globalMultiples.indexOf(mult) === -1) {
globalMultiples.push(mult);
}
}
}
return globalMultiples.length;
};
EDIT : You won't have any stack error but choosing big values for the range may hang your browser.
If I have n balls and k containers then this -> ( (n+k-1)! / n!(k-1)! ) will work out how many combinations there are.
I am having difficulty changing this to produce a list of all combinations in javascript.
In a function taking an array of balls and some amount of containers.
combinations([1,2,3,4,5,6], 3)
Each container can have any number of balls and containers can be empty.
Here is something i attempted but im only getting one ball in each container.
function generateCombinations(array, r, callback) {
function equal(a, b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
function values(i, a) {
var ret = [];
for (var j = 0; j < i.length; j++) ret.push(a[i[j]]);
return ret;
}
var n = array.length;
var indices = [];
for (var i = 0; i < r; i++) indices.push(i);
var final = [];
for (var i = n - r; i < n; i++) final.push(i);
while (!equal(indices, final)) {
callback(values(indices, array));
var i = r - 1;
while (indices[i] == n - r + i) i -= 1;
indices[i] += 1;
for (var j = i + 1; j < r; j++) indices[j] = indices[i] + j - i;
}
callback(values(indices, array));
}
count = 0
generateCombinations([1,2,3,4,5,6,7,8,9,1],3,function(first){
$("#hello").append(first+"<br />")
count = count +1
})
$("#hello").append(count)
You can do it in this way:
var containers = [];
// n - number of balls, k - number of containers
function dfs(n, k) {
// Ending point of recursion, all balls are placed
if(n == 0) {
var output = [];
for(var i = 0; i < k; i++) {
output.push('{' + containers[i].join(', ') + '}');
}
output = '[' + output.join(', ') + ']';
console.log(output);
return;
}
// Try to put ball #n
for(var i = 0; i < k; i++) {
containers[i].push(n);
// Now we have placed ball #n, so we have 1 .. n - 1 balls only
dfs(n - 1, k);
// Remove ball when back to use again
containers[i].pop();
}
}
var n = 4;
var k = 3;
for(var i = 0; i < k; i++) {
containers[i] = [];
}
dfs(n, k);
I initially thought you wanted all the combinations of k elements out of n, but your problem is different, it's partitioning n elements in k parts.
When going through the elements, at each steps, you may choose to put the current element in any container, that's k possibilities. In total, you will have kn possible solutions.
Therefore, it would be faster to iterate through all the solutions, rather than storing them in an array.
You can represent a solution as a unique number in base k, with n digits, and iterate through the solutions by incrementing that number.
In your example, the base is 3, and the number of digits is 6. The first solution is to put all the balls in container 0, ie.
000000
The next solution is to put all the balls in container 0, excepted the last which goes in container 1.
000001
...
000002
000010
000011
000020
Hopefully you should get the idea.
I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6?
How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6.
I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches.
Then I would use the % operator the same way to get every element out that doesn't return 0.
The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this?
My Code is:
var allnumbers = [],j;
var biggestnumber = "999999999999999999999999999999999999999999999999999999999999";
function howmanynumbers(digits,numbers,divideWith){
if (digits && numbers && divideWith){
for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){
allnumbers.push(i);
}
for (j = 0; j < numbers.length; j++ ){
var matchit = new RegExp(numbers[j]);
}
//not expected to work, I just had this in for reference
if ( String(allnumbers[i]).match(matchit) != [""]){
j = 0;
allnumbers.splice(i,1);
var matchit = new RegExp(numbers[j])
}
}
else {
return false;
}
}
This is my take on the entire solution:
var i;
var allowedDigitsPattern = /^[0-5]+$/i;
var numbers = [];
for (i = 100000; i < 555555; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
And you can look at your results like this:
document.write('There are ' + numbers.length + ' numbers<br>');
// write out the first ten!
for (i = 0; i < 10; i++) {
document.write(numbers[i] + '<br>');
}
Update based on comments...
The configurable version of this would be:
var i;
var lowestDigit = 0;
var highestDigit = 5;
var numberOfDigits = 6;
var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi');
var smallestNumber = '1';
for (i = 1; i < numberOfDigits; i++) {
smallestNumber += '0';
}
var biggestNumber = '';
for (i = 0; i < numberOfDigits; i++) {
biggestNumber += highestDigit.toString();
}
var numbers = [];
for (i = smallestNumber; i < biggestNumber; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
document.write('There are ' + numbers.length + ' numbers<br>');
You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.