CCC2

My approach for the second community coding challenge hosted by SAP

by megges

JavaScript

function collatzStep(n)
{
	if (n % 2 == 0)
  {
  	return n/2;
  }
  
  return 3*n+1;
}

function longestCollatzChainNumber(limit)
{
	var history = new Array(limit).fill(0)
  var longestChainIndex = 0
  
  for (var i = 0; i < history.length; i++)
  {
  	var unknownIndices = []
    var currentIndexInChain = i
    
    while (currentIndexInChain >= history.length || history[currentIndexInChain] == 0 && currentIndexInChain != 0)
    {
    	unknownIndices.push(currentIndexInChain)
      currentIndexInChain = collatzStep(currentIndexInChain + 1) - 1
    }
    
    var chainLengthOffset = 1
    
    while (unknownIndices.length != 0)
    {
    	var topIndex = unknownIndices.pop()
      
      if (topIndex < history.length)
      {
      	history[topIndex] = history[currentIndexInChain] + chainLengthOffset
      }
      
      chainLengthOffset++
    }
    
    if (history[i] > history[longestChainIndex])
    {
    	longestChainIndex = i
    }
  }
  
  return longestChainIndex + 1
}

console.log(longestCollatzChainNumber(1000000))