function redistribute(arr){ var max = Math.max.apply(null, arr); var maxPos = arr.indexOf(max); var toAdd = Math.floor(max / (arr.length-1)); var left = max % (arr.length-1); if(toAdd == 0){ left = 0; for(var i = 1; i <= max; i++){ arr[(i + maxPos)%(arr.length)] += 1; } arr[maxPos] = 0; } else{ arr = arr.map((a)=>(a+toAdd)); arr[maxPos] = left; } return arr; } var states = []; var state = require("fs").readFileSync("input.txt").toString().split("\t").map((a)=>(parseInt(a))); var i = 0; while(states.indexOf(state.join(",")) == -1){ console.log(state, i); states.push(state.join(",")); i++; state = redistribute(state); } console.log(state,i);