JSFiddle - React, Tailwind, and code Playground
by mckennatim
HTML
<div>
<h4>find the last duplicate index</h4>
<input type="text" id="inp" value="[6,3,7,8,3,4,6,7]" onchange="dorev()"></input><br>
The find last occurance of <input type="text" id="inp2" value="8" onchange="dorev()" size="1"></input><br> in the sorted array below<br>
<span id="out"></span>
</div>
JavaScript
var consol = {}
consol.log = function(x){
$("#out").html($("#out").html()+x+"<br>")
}
function findLastDup(a,v){
var l=0, r=a.length-1, m=Math.floor((r+l)/2)
consol.log(' '+l+' '+m+' '+r)
function theIdxs(m){
var to = m
var ret =[]
ret[0]=m
ti=to
//check both ways for more or the same
while (ti-1<=0 && a[ti]==a[ti-1]){
ti--
ret.push(ti)
}
ti=to
while (ti+1<a.length-1 && a[ti]==a[ti+1]){
ti++
ret.push(ti)
}
var max = Math.max.apply(null,ret)
consol.log(JSON.stringify(ret))
return max
}
while (true){
if (v==a[m]){
consol.log(m)
consol.log('found at m')
return theIdxs(m)
}else if(v==a[m+1]){
consol.log(m)
consol.log('You have to stop at 2 items and check the second otherwise it will keep going back to the same place')
consol.log('found at m+1')
return theIdxs(m+1)
}else if (v>=a[m]){
l=m;
}else {
r=m;
}
m=Math.floor((r+l)/2)
consol.log(' '+l+' '+m+' '+r)
if (r-l <2){
consol.log('not there')
return -1
}
}
}
function dorev(){
$("#out").html('')
var str =$("#inp").val()
var val = parseInt($("#inp2").val())
var arr = str.slice(1,-1).split(',').map(function(e){return parseInt(e)})
var sarr = arr.sort(function(a,b){return a-b})
consol.log(sarr)
consol.log("The left, right and middle progression")
var last = findLastDup(sarr,val)
consol.log('the last occurrance of <b>'+ sarr[last] + '</b> is index<b> '+last+'</b')
}
dorev($("#inp").val())