Related
When I run this program I am only getting the even number count and the odd sum. The odd count and even sum just gives me 0 every time.
Does anyone have any idea what I am missing? Thanks!
I am trying to generate 100 random numbers and keep count of the evens/odds and then get the sum of each.
var min = 1;
var max = 1000;
var randomNumArray = []
var oddCount = []
var evenCount = []
var oddSum = []
var evenSum = []
function isEven(x){
if (x % 2 == 0)
return true;
else
return false;
}
function sumOfArray(evenSum){
for(i = 0; i< evenSum.length; i++){
if (isEven){
return(evenSum);
}
else{
return (oddSum);
}
}
}
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
randomNumArray.push(randNumber);
}
for( i = 0; i< randNumber.length; i++){
if (isEven(evenCount[i])){
return evenCount;
}
else{
return oddCount;
}
}
console.log('Even Number Count: ' + evenCount);
console.log('Odd Number Count: ' + oddCount);
console.log('Sum Even: ' + evenSum);
console.log('Sum Odd: ' + oddSum);
I would just use 1 function to check if its even or odd and then decide to add the sum by the number itself and the count by 1. You are making it way more complicated and I'm wondering why u are using arrays.
Try something like this:
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
if(isEven(randNum)){
evenSum = evensum+randNum;
evenCount ++;
}else{
oddSum= oddSum+randNum;
oddSum++;
}
}
var oddCount = 0
var evenCount = 0
for(i=0; i<randomNumArray.length; i++) {
if(randomNumArray[i] % 2 == 0) {
evenCount++
} else {
oddCount++
}
};
Something like that should work?
I have quite complicated array which I need to transform to specific format. The array looks like this:
arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
Each array in my output need contains only 5 values - 3 first values always will be the same like in input. The next 2 values should contain code and the lowest value from the rest of the array. So this case output will look like this:
output = [["name1",51,1,"code1",3],["name2",52,0,"code2",4],["name3",51,2,"code6",1],["name4",55,5,"code8",1],["name5",54,2,"code9",5]];
For start I think the best is use loop for and if instruction, but I don't know how to cope with this later on.
for (i=0; i<arr.length; i++) {
if (arr[i]>5) {
//dont know what to put here
}
}
My solution:
arr = [
["name1",51,1,"code1",3],
["name2",52,0,"code2",4,"code3",6],
["name3",51,2,"code4",3,"code5",6,"code6",1],
["name4",55,5,"code7",7,"code8",1],
["name5",54,2,"code9",5,"code10",8]
];
function process_array(in_array) {
var output = [];
/* check each element in array */
in_array.forEach(function(sub_array){
/* store new sub array here*/
var last_sub_out = [];
var code;
var lowest_num = Number.MAX_VALUE;
/* check sub array
#value is value of sub_array
#index is index of that value.
*/
sub_array.forEach(function(value, index){
/* add first 3 values */
if(index < 3) {
last_sub_out.push( value );
return;
}
/* checking only numbers(even index: 4,6,8, ...) */
if(index % 2 == 0) {
if(value < lowest_num) {
code = sub_array[index - 1];
lowest_num = value;
}
}
});
/* add found code with lowest number */
last_sub_out.push(code, lowest_num);
output.push( last_sub_out );
/* LOG */
document.write(last_sub_out.join(', ') + "</br>");
});
return output;
}
var out = process_array(arr);
var arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
var out=[];
for (i=0; i < arr.length; i++) {
if (arr[i].length>5) {
out[i] = [arr[i][0], arr[i][1], arr[i][2]];
c = [arr[i][3], arr[i][4]];
for (j=0; j < (arr[i].length - 5)/2; j++){
if (c[1] > arr[i][6+2*j]){
c = [arr[i][5+2*j], arr[i][6+2*j]];
}
}
out[i][3] = c[0]; out[i][4] = c[1];
} else {
out[i] = arr[i]
}
}
Try:
var arr = [["name1",51,1,"code1",3],["name2",52,0,"code2",4,"code3",6],["name3",51,2,"code4",3,"code5",6,"code6",1],["name4",55,5,"code7",7,"code8",1],["name5",54,2,"code9",5,"code10",8]];
var output = [], startIndex = 3, i = 0;
while(i < arr.length){
var item = arr[i++], j = startIndex, count = 0, min = Infinity, code;
while(j < item.length){
count++ % 2 && item[j] < min && (min = item[j], code = item[j-1]);
j++
}
item.splice(startIndex, item.length, code, min);
output.push(item)
}
document.write("<pre>" + JSON.stringify(output, null, 4) + "<pre>");
I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);
The following error occours
Thu May 23 07:14:53.437 JavaScript execution failed: map reduce failed:{
"errmsg" : "exception: JavaScript execution failed: TypeError: Cannot read property 'product_category' of undefined near '(values[i].product_category)' (line 21)",
"code" : 16722,
"ok" : 0
at src/mongo/shell/collection.js:L970
My map and reduce function are:
map1 = function()
{
emit({Product_id:this.Product_id
},
{
product_category:this.product_category
});
}
reduce1 = function(key, values)
{
var ref = new Array();
var count = 0;
var tmp="";
var pdt_array = new Array();
for (var i = 1; i <= values.length; i++) {
if( i == 1 )
{
pdt_array_array[i] = values[i];
}
else
{
tmp = values[i];
while(i > 1)
{
if(tmp == pdt_array[i])
{
ref.push(values[i].product_category);
count++;
}
i--;
}
pdt_array[i] = tmp;
tmp = "";
}
}
return {product_category:ref, Count:count}
}
db.DummyReverse.mapReduce(map1, reduce1, {out:{reduce:"product_count_while"}})
The issue is that you are not returning the same format from reduce function as you are emitting as value. Since reduce function can be called 0, once or multiple times for each key you must use the exact same format in all of those cases and you cannot assume that your reduce function will be called only once.
Javascript arrays are 0-indexed. So your last for-run want to access a array index, which doesn't exist. I hope I interpret your code right.
[...]
for (var i = 0; i < values.length; i++) {
if ( i == 0) {
pdt_array_array[i] = values[i];
} else {
tmp = values[i];
while(i > 0) {
if(tmp == pdt_array[i]) {
ref.push(values[i].product_category);
count++;
}
i--;
}
pdt_array[i] = tmp;
tmp = "";
}
}
[...]
Take notice at for (var i = 0; i < values.length; i++). So the n-th element has the index n-1. The last element length-1.
Remarks: Are you sure you get no infinite loop with the for-loop increasing i and in the while decreasing it?
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.