Добавление текста согласно анимации в React - PullRequest
0 голосов
/ 01 августа 2020

Итак, я пытаюсь создать Визуализатор сортировки слиянием

В основном я пытаюсь добавить текст, который говорит о текущей итерации алгоритма, например

«Сравнивая 4 и 5, 5 больше 4, поэтому ... "

Вот мой код на данный момент

export default class SortingVisualizer extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      array: [],
    };
  }
  componentDidMount() {
    this.resetArray();
  }
  resetArray() {
    const array = [];
    for (let i = 0; i < NUMBER_OF_ARRAY_BARS; i++) {
      array.push(randomIntFromInterval(5, 730));
    }
    this.setState({array});
  }
  mergeSort() {    
    const text=[];
   // console.log(this.state.array); array is not sorted
    const animations = getMergeSortAnimations(this.state.array);
   // const text = document.getElementsByTagName('h1')[1]; //get the h1 tag 
   // console.log(this.state.array); array is now sorted
   // console.log(animations);
    const wholearray= document.getElementsByClassName('array-container');
    
    const arrayBars = document.getElementsByClassName('array-bar');
    for (let i = 0; i < animations.length; i++) {
     // const arrayBars = document.getElementsByClassName('array-bar');
      const isColorChange = i % 3 !== 2;
      if (isColorChange) {
        
        const [barOneIdx, barTwoIdx] = animations[i];
        text.push([barOneIdx,barTwoIdx]);
       // text.innerHTML= "comparing" + barOneIdx+"and" +barTwoIdx;
        const barOneStyle = arrayBars[barOneIdx].style;        
        const barTwoStyle = arrayBars[barTwoIdx].style;

        const color = i % 3 === 0 ? 'yellow' : 'red';
        setTimeout(() => {
          
          barOneStyle.backgroundColor = color;
          barTwoStyle.backgroundColor = color;
        }, i * ANIMATION_SPEED_MS);
      } 
      else {
        setTimeout(() => {
          
          
          
          const [barOneIdx, newHeight] = animations[i];
          const barOneStyle = arrayBars[barOneIdx].style;
       //   console.log(arrayBars[barOneIdx].innerHTML);
          arrayBars[barOneIdx].innerHTML = newHeight;
          barOneStyle.height = `${newHeight}px`;
        }, i * ANIMATION_SPEED_MS);
      }
    }
    return text;
  }
  render() {
    const {array} = this.state;
    return (
        
      <div className="array-container">
         <h1> Merge Sort </h1>
        <button onClick={() => this.resetArray()}>Generate New Array</button>
        <button onClick={() => this.mergeSort()}>Merge Sort</button>
        
        {this.state.array.map((value, idx) => (
          <div
          className="array-bar"
            key={idx}
            style={{
              color: 'black', 
              width: `50px`,
              backgroundColor: 'yellow',
              height: `${value}px`,
            }}>{value}
            <div>{console.log("1")}</div></div>
        ))}
          </div>
    );
  }
}

функция getMergeSortAnimations: -

export function getMergeSortAnimations(array) {
  const animations = [];
  if (array.length <= 1) return array;
  const auxiliaryArray = array.slice();
  mergeSortHelper(array, 0, array.length - 1, auxiliaryArray, animations);
  return animations;
}
function mergeSortHelper(
  mainArray,
  startIdx,
  endIdx,
  auxiliaryArray,
  animations,
) {
  if (startIdx === endIdx) return;
  const middleIdx = Math.floor((startIdx + endIdx) / 2);
  mergeSortHelper(auxiliaryArray, startIdx, middleIdx, mainArray, animations);
  mergeSortHelper(auxiliaryArray, middleIdx + 1, endIdx, mainArray, animations);
  doMerge(mainArray, startIdx, middleIdx, endIdx, auxiliaryArray, animations);
}
function doMerge(
  mainArray,
  startIdx,
  middleIdx,
  endIdx,
  auxiliaryArray,
  animations,
) {
  let k = startIdx;
  let i = startIdx;
  let j = middleIdx + 1;
  while (i <= middleIdx && j <= endIdx) {

    animations.push([i, j]); //compare

    animations.push([i, j]);//revert
    if (auxiliaryArray[i] <= auxiliaryArray[j]) {
      // We overwrite the value at index k in the original array with the
      // value at index i in the aux array.
      animations.push([k, auxiliaryArray[i],mainArray[k]]);
      mainArray[k++] = auxiliaryArray[i++];
    } else {
      // We overwrite the value at index k in the original array with the
      // value at index j in the aux array.
      animations.push([k, auxiliaryArray[j]]);
      mainArray[k++] = auxiliaryArray[j++];
    }
  }
  while (i <= middleIdx) {
    animations.push([i, i]);
    animations.push([i, i]);
    animations.push([k, auxiliaryArray[i],mainArray[k]]);
    mainArray[k++] = auxiliaryArray[i++];
  }
  while (j <= endIdx) {
    animations.push([j, j]);
    animations.push([j, j]);
    animations.push([k, auxiliaryArray[j],mainArray[k]]);
    mainArray[k++] = auxiliaryArray[j++];
  }
}

export default  getMergeSortAnimations;

Я пытался поставить text.innerHTML= "comparing" + barOneIdx+"and" +barTwoIdx; в mergesort (), но он не обновляется на веб-сайте постоянно, я получаю только последние индексы в качестве вывода. Например, если мой массив имеет длину 10. Я получаю результат как Сравнение 9 и 9, т.е. только последнее сравнение ..

Итак, как мне написать текст, чтобы изобразить живую итерацию алгоритма

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...