why my javascript is showing value not founded? - javascript

I am trying to do a binary search in an array but my javascript is showing no value founded even when I entered a number that in the array in the prompt input
var array = [10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 100, 102, 105, 200, 250, 300, 320, 350];
var search = parseInt(prompt("enter what you search for"));
var first = 0,
last = array.length - 1,
position = 0,
middle, flag = false;
while ((flag == false) && (first <= last)) {
middle = ((first + last) / 2);
if (array[middle] == search) {
flag = true;
position = middle;
} else
if (array[middle] > search)
last = middle - 1;
else
first = middle + 1;
}
if (flag)
document.write("</br>value founded in position " + position);
else
document.write("</br>value not founded ");

middle value calculation.
middle = Math.round(first + ((last - first) / 2));
// Your code..
var array =[10,20,30,40,50,60,70,80,90,95,100,102,105,200,250,300,320,350] ;
var search= 20; //parseInt(prompt ("enter what you search for"));
var first=0, last=array.length-1,
position=0,
middle ,
flag=false;
while((flag==false) && (first <=last)) {
middle = Math.round(first + ((last - first) / 2)); //((first+last)/2); low + (last - low)/2
if (array[middle]==search){
flag=true;
position=middle ;
}else if(array[middle]>search) {
last=middle-1 ;
}
else {
first= middle+1;
}
}
if (flag)
document.write ("</br>value founded in position "+position);
else
document.write("</br>value not founded ");

For now when you do middle = ((first + last) / 2); it puts the number with floating point to the middle. However, you need to have integer number here. In order to make it you should wrap your calculation with Math.round() or Math.floor().
So you will get:
middle = Math.round((first + last) / 2);

Related

Index Values Do Not Equal Answers

I am creating a hangman game and need the green rectangles to change to red rectangles when the inputted answer by the player is INCORRECT. The total calculating function works, the input !==answers does not work which is what I need help with.
var total = 0;
gameboard.fillStyle = 'green';
gameboard.fillRect(10, 30, 30, 30)
gameboard.fillRect(80, 30, 30, 30)
gameboard.fillRect(150, 30, 30, 30)
$('#total_score').on('click', calculate);
function calculate() {
for (var index = 0; index < 14; index = index + 1) {
if ($('#' + index).val() == answers[index]) {
total = total + 1;
}
if ($('#' + index).val() !== answers[index]) {
gameboard.fillStyle = 'red';
gameboard.fillRect(10, 30, 30, 30)
}
}
$('#display_total').html(total);
total = 0;
};

Median of an array in Javascript?

I am trying to find the median of an array.
I have done quite some research and if this seemed to be asked several times, no answers were satisfying.
Creating my array works perfectly but when I call the function the array is sorted but it returns different values, from NaN to the first value of the array
How to find the median value of the length, and then from it's index find the median value of the array?
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(enterValues);
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half] + ar1[half] + 1) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
(ps:to stop filling the array just enter without value.)
You have 2 problems in your code:
You calculate half before you fill the array so it will always be 0.
You save the numbers as string so when you add them you don;t get the right results.
Working :
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(+enterValues);
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half] + ar1[half] + 1) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
var ar1 = [];
while (true) {
var enterValues = prompt("enter your values");
if (enterValues != "") {
ar1.push(parseFloat(enterValues));
} else {
break;
}
}
function calcMedian() {
var half = Math.floor(ar1.length / 2);
ar1.sort(function(a, b) { return a - b;});
if (ar1.length % 2) {
return ar1[half];
} else {
return (ar1[half-1] + ar1[half]) / 2.0;
}
}
console.log(ar1);
console.log(ar1.length);
console.log(calcMedian());
console.log(ar1);
Math.floor(ar1.length) will return (for example) 4 is the length is 8. However, if you do ar1[4] it will actually return the fifth item in the array as the array index starts at zero. So ar1[4-1] will return the fourth item, add it to ar1[4] which is the fifth item and divide it by two to find the median. If the length is odd, it will return (for example) 3 if the length is 7. It then retrieves arr[3] which is the fourth item which is the median.
let values = [2, 56, 3, 41, 0, 4, 100, 23];
values.sort(function(a,b) {
return a - b;
});
let lowMiddle = Math.floor( (values.length - 1) / 2);
let highMiddle = Math.ceil( (values.length - 1) / 2);
let median = ( values[lowMiddle] + values[highMiddle]) / 2;
console.log(median);

how to calculate the ways of a big number split by some small numbers in js

For example: There is a total number 1000, and how many ways to equal 1000 using 100/50/20/10/5/1. I have found a idea about this. But obviously, that's not good. So does anyone have some other good ideas to cover it?
total = prompt('you can input number 1-1000, but 1000 will take a LOONG time');
count = 0;
t100 = total;
function money() {
for (var i100 = Math.floor(t100 / 100); i100 >= 0; i100--) {
var t50 = t100 - i100 * 100;
for (var i50 = Math.floor(t50 / 50); i50 >= 0; i50--) {
var t20 = t50 - i50 * 50;
for (var i20 = Math.floor(t20 / 20); i20 >= 0; i20--) {
var t10 = t20 - i20 * 20;
for (var i10 = Math.floor(t10 / 10); i10 >= 0; i10--) {
var t5 = t10 - i10 * 10;
for (var i5 = Math.floor(t5 / 5); i5 >= 0; i5--) {
var t1 = t5 - i5 * 5;
count++;
console.log(i100 + ' 100' + i50 + ' 50' + i20 + ' 20' + i10 + ' 10' + i5 + ' 5' + t1 + ' 1');
}
}
}
}
}
alert('The total number ' + total + ' is ' + count);
}
money()
No idea if it's correct but a little idea that popped to my head:
You know that with the bills/coins given, you can always fill up to the amount you need (value). If at the same time, you assume that you will always chose the highest possible bill / coin for the remainder I think you could do this:
If you use 100 bills you have floor(value / 100) possibilities (You can use 1 x 100, 2 x 100... )
If you don't use 100 but 50 you have floor(value / 50) possibilities
If you don't use 50 but 20 you have floor(value /20) possibilities
and so on. Add those up and you have a total of possibilities.
Let me know if I'm missing something.
I don't know about coding in js but you could try an algorithm like this one, which should be much more performant timely speaking. I'll try to make it as clear as possible :
availableCoins = [100, 50, 20, 10, 5] // all available coins exept 1
numberCoins = availableCoins.Length
mapResults = new Map[(int,int),int]
money(int total, int indexCoin){
if ( indexCoin == numberCoins ) {
return 1 // only coin 1 is available, there is only one solution
}
elseif ( mapResults.containsKey((total,indexCoin)) ) {
return mapResults((total,indexCoin)) // if the result has already been computed
}
else {
int count = 0
int currentCoin = availableCoin[indexCoin]
int upperbound = floor(total / currentCoin) // compute it before to avoid useless computation
for (int i = 0; i <= upperbound; i++) {
count += money(total - i * currentCoin, indexCoin + 1) // we assume only i of the current coin will be use
}
mapResults((total,indexCoin)) = count
return count
}
}
money(1000, 0)
Let me know if I have missed something or if it is not clear.
I let you adapt it to js.
I have got a expression from my colleague, and here it is:
//n is the total number
Change(n,m) {
if(n===0) return 0;
if(n<0 || m === 0) return 0;
var dimes = [1, 5, 10, 20, 50, 100];
return (change(n, m-1)+change(n-dimes[m-1], m));
}

Editing jquery-countdown to fit my HTML element

I've collected a nice jQuery countdown script from here. It needs no configuration but a great opensource project. But where I want to set is a smaller place like 50%. So, now I want to make it 50% on both width and height. First of all I opened digits.png with photoshop and made it 50%, then I opened jquery.countdown.js and the code is following:
jQuery.fn.countdown = function(userOptions)
{
// Default options
var options = {
stepTime: 60,
// startTime and format MUST follow the same format.
// also you cannot specify a format unordered (e.g. hh:ss:mm is wrong)
format: "dd:hh:mm:ss",
startTime: "01:12:32:55",
digitImages: 6,
digitWidth: 67,
digitHeight: 90,
timerEnd: function(){},
image: "digits.png",
continuous: false
};
var digits = [], intervals = [];
// Draw digits in given container
var createDigits = function(where)
{
var c = 0;
// Iterate each startTime digit, if it is not a digit
// we'll asume that it's a separator
for (var i = 0; i < options.startTime.length; i++)
{
if (parseInt(options.startTime[i]) >= 0)
{
elem = $('<div id="cnt_' + c + '" class="cntDigit" />').css({
height: options.digitHeight,
float: 'left',
background: 'url(\'' + options.image + '\')',
width: options.digitWidth
});
elem.current = parseInt(options.startTime[i]);
digits.push(elem);
margin(c, -elem.current * options.digitHeight * options.digitImages);
if (options.continuous === true)
{
digits[c]._max = function(){ return 9; };
}
else
{
// Add max digits, for example, first digit of minutes (mm) has
// a max of 5. Conditional max is used when the left digit has reach
// the max. For example second "hours" digit has a conditional max of 4
switch (options.format[i])
{
case 'h':
digits[c]._max = function(pos, isStart) {
if (pos % 2 == 0)
return 2;
else
return (isStart) ? 3: 9;
};
break;
case 'd':
digits[c]._max = function(){ return 9; };
break;
case 'm':
case 's':
digits[c]._max = function(pos){ return (pos % 2 == 0) ? 5: 9; };
}
}
++c;
}
else
{
elem = $('<div class="cntSeparator"/>').css({float: 'left'})
.text(options.startTime[i]);
}
where.append(elem)
}
};
// Set or get element margin
var margin = function(elem, val)
{
if (val !== undefined)
{
digits[elem].margin = val;
return digits[elem].css({'backgroundPosition': '0 ' + val + 'px'});
}
return digits[elem].margin || 0;
};
var makeMovement = function(elem, steps, isForward)
{
// Stop any other movement over the same digit.
if (intervals[elem])
window.clearInterval(intervals[elem]);
// Move to the initial position (We force that because in chrome
// there are some scenarios where digits lost sync)
var initialPos = -(options.digitHeight * options.digitImages *
digits[elem].current);
margin(elem, initialPos);
digits[elem].current = digits[elem].current + ((isForward) ? steps: -steps);
var x = 0;
intervals[elem] = setInterval(function(){
if (x++ === options.digitImages * steps)
{
window.clearInterval(intervals[elem]);
delete intervals[elem];
return;
}
var diff = isForward ? -options.digitHeight: options.digitHeight;
margin(elem, initialPos + (x * diff));
}, options.stepTime / steps);
};
// Makes the movement. This is done by "digitImages" steps.
var moveDigit = function(elem)
{
if (digits[elem].current == 0)
{
// Is there still time left?
if (elem > 0)
{
var isStart = (digits[elem - 1].current == 0);
makeMovement(elem, digits[elem]._max(elem, isStart), true);
moveDigit(elem - 1);
}
else // That condition means that we reach the end! 00:00.
{
for (var i = 0; i < digits.length; i++)
{
clearInterval(intervals[i]);
clearInterval(intervals.main);
margin(i, 0);
}
options.timerEnd();
}
return;
}
makeMovement(elem, 1);
};
$.extend(options, userOptions);
createDigits(this);
intervals.main = setInterval(function(){ moveDigit(digits.length - 1); },
1000);
};
I tried changing some variables, digitWidth: 67 to digitWidth: 34 then digitHeight: 90 to digitHeight: 45 with no success. I want to make the countdown timer just half than the original. Can you suggest any change anywhere in the code, please?
Update: This is digits.png, 50% than original!
I also changed associated div's like #holder with no success.
Following is the current situation of the timer. The red marked places are the problems I mean misplaced.
You didn't resize digits.png correctly - it's too high, so digitHeight doesn't match your image.
See demo with an image that has 50% height (plugin code unchanged):
http://jsfiddle.net/lhoeppner/RGyPQ/
See the section with the image param:
$('#counter').countdown({
stepTime: 60,
digitWidth: 34,
digitHeight: 45,
format: 'hh:mm:ss',
startTime: "12:32:55",
timerEnd: function () {
alert('end!!');
},
image: "http://s21.postimg.org/nfgjv6b7r/digits2.png"
});

Math.ceil to nearest five at position 1

Okay....
I have a lot of uncontrolled numbers i want to round:
51255 -> 55000
25 -> 25
9214 -> 9500
13135 -> 15000
25123 -> 30000
I have tried modifying the numbers as string and counting length....
But is there a simple way using some Math function maybe?
Here's my late answer. Uses no Math methods.
function toN5( x ) {
var i = 5;
while( x >= 100 ) {x/=10; i*=10;}
return ((~~(x/5))+(x%5?1:0)) * i;
}
DEMO: http://jsbin.com/ujamoj/edit#javascript,live
[51255, 24, 25, 26, 9214, 13135, 25123, 1, 9, 0].map( toN5 );
// [55000, 25, 25, 30, 9500, 15000, 30000, 5, 10, 0]
Or this is perhaps a bit cleaner:
function toN5( x ) {
var i = 1;
while( x >= 100 ) {x/=10; i*=10;}
return (x + (5-((x%5)||5))) * i;
}
DEMO: http://jsbin.com/idowan/edit#javascript,live
To break it down:
function toN5( x ) {
// v---we're going to reduce x to the tens place, and for each place
// v reduction, we'll multiply i * 10 to restore x later.
var i = 1;
// as long as x >= 100, divide x by 10, and multiply i by 10.
while( x >= 100 ) {x/=10; i*=10;}
// Now round up to the next 5 by adding to x the difference between 5 and
// the remainder of x/5 (or if the remainder was 0, we substitute 5
// for the remainder, so it is (x + (5 - 5)), which of course equals x).
// So then since we are now in either the tens or ones place, and we've
// rounded to the next 5 (or stayed the same), we multiply by i to restore
// x to its original place.
return (x + (5-((x%5)||5))) * i;
}
Or to avoid logical operators, and just use arithmetic operators, we could do:
return (x + ((5-(x%5))%5)) * i;
And to spread it out a bit:
function toN5( x ) {
var i = 1;
while( x >= 100 ) {
x/=10;
i*=10;
}
var remainder = x % 5;
var distance_to_5 = (5 - remainder) % 5;
return (x + distance_to_5) * i;
}
var numbers = [51255, 25, 9214, 13135, 25123, 3, 6];
function weird_round(a) {
var len = a.toString().length;
var div = len == 1 ? 1 : Math.pow(10, len - 2);
return Math.ceil(a / 5 / div) * div * 5;
}
alert(numbers.map(weird_round));
Also updated for numbers below 10. Won't work properly for negative numbers either, just mention if you need this.
DEMO
I'm not sure why, but I thought it would be fun with regular expressions:
var result = +(number.toString().replace(/([1-9])([0-9])(.+)/, function() {
return Math.ceil(+(arguments[1] + '.' + arguments[2])) * 10 - (+arguments[2] < 5?5:0) + arguments[3].replace(/./g, '0');
}));
Working Demo
with(Math) {
var exp = floor(log(number)/log(10)) - 1;
exp = max(exp,0);
var n = number/pow(10,exp);
var n2 = ceil(n/5) * 5;
var result = n2 * pow(10,exp);
}
http://jsfiddle.net/NvvGf/4/
Caveat: only works for the natural numbers.
function round(number) {
var numberStr = number + "",
max,
i;
if (numberStr[1] > '4') {
numberStr[0] = parseInt(numberStr[0]) + 1;
numberStr[1] = '0';
} else {
numberStr[1] = '5';
}
for (i = 2; max = numberStr.length; i < max; i += 1) {
numberStr += '0';
}
return parseInt(numberStr);
}
Strange coincidence, I wrote something really similar not so long ago!
function iSuckAtNames(n) {
var n = n.toString(), len = n.length, res;
//Check the second number. if it's less than a 5, round down,
//If it's more/equal, round up
//Either way, we'll need to use this:
var res = parseFloat(n[0]) * Math.pow(10, len - 1); //e.g. 5 * 10^4 = 50000
if (n[1] <= 5) {
//we need to add a 5 right before the end!
res += 5 * Math.pow(10, len - 2);
}
else {
//We need another number of that size
res += Math.pow(10, len - 1);
}
return res;
}

Categories

Resources