Monesha_G_Code

mail@pastecode.io avatar
unknown
javascript
3 years ago
1.9 kB
10
Indexable
Never
/* Given a two dimensional array of string like.
<”luke”, “shaw”>;
<”wayne”, “rooney”>;
<”rooney”, “ronaldo”>;
<”shaw”, “rooney”>;
 
Where the first string is “child”, second string is “Father”. And given “ronaldo” we have to find his no of
grandchildren Here “ronaldo” has 2 grandchildren. So our output should be 2. */


const arr = [
	["luke", "shaw" ],
  ["wayne", "rooney"],
  ["rooney", "ronaldo"],
  ["shaw", "rooney"]
]

/* [child, parent]
find granchildren */

function findGrandChild(arr, gFather){
	var sons = []
  var gsons = []
  var index = []
  /* above is index of the granfather */
  var indexofSons = []
  
  /* iterate on the arr
  item -> inner arr
  return index of all the arrays that have the value "gfather"
  now get the first elem of these indexes to get "sons"
  
  iterate through the array to get index of "sons"
  usinfg index, grab the first elem of sons to find gSons */
  
  for(let i =0; i<arr.length; i++){
  		/* first */  
      if(arr[i][0] !== gFather){
      		if(arr[i].indexOf(gFather) != -1){
      				index.push(i)
     			 }  
      }
  }
  
  for (let i = 0; i<index.length; i++){
     sons.push( arr[index[i]][0])
  }
  console.log("list of sons:", sons)
  
  
  sons.map(sonName=>{
  		/* console.log("crruent son: ", sonName) */
  		for(let i=0; i<arr.length; i++){
      
          if(arr[i][0] !== sonName) {
          		if(arr[i].indexOf(sonName)!== -1  ){ 
      		  			
             			indexofSons.push(i)
      				}
          }
      }
  })
  
  for (let i =0; i<indexofSons.length; i++){
      /* get the grandsons */
     /*  console.log(arr[indexofSons[i]][0]) */
     gsons.push( arr[indexofSons[i]][0])
  }
  console.log("list of grandsons: ", gsons)
  return gsons.length
}

console.log(findGrandChild(arr, "wayne"))