Рефакторинг алгоритма Fibonacci

Как я тестировал в StackBlitz, он работает нормально для меня, взгляните на:

Parent Component HTML:

PARENT

Parent Component TS:

import { Component } from '@angular/core';
import { DataService } from './data.service';

/** @title Simple form field */
@Component({
  selector: 'form-field-overview-example',
  templateUrl: 'form-field-overview-example.html',
  styleUrls: ['form-field-overview-example.css'],
  providers: [DataService]
})
export class FormFieldOverviewExample {

  constructor(private service: DataService) {

  }
  parentValue = {
    "userId": 112,
    "id": 1121,
    "title": "masxsat",
    "body": "teasdas"
  }
  buttonClicked() {
    this.service.getData()
    this.service.data.subscribe(value => {
      console.log(value)
      this.parentValue = value;
    })
  }
}

Child Component HTML:

Child

{{inputChildVar | json}}

Child Component TS:

import { Component, OnInit, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges {

  @Input() inputChildVar

  constructor() { }
  ngOnChanges() {
    console.log(this.inputChildVar)
  }
  ngOnInit() { }
}

Data.Service.ts:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  data = new BehaviorSubject(null)

  constructor(
    private http: HttpClient
  ) { }


  getData() {
    this.get()
      .then(response => {
        this.data.next(response);
      })
  }

  get(): Promise {
    const url = `https://jsonplaceholder.typicode.com/posts/1`;
    return this.http.get(url)
      .toPromise()
      .catch(this.handleError);
  }

  // handler for error in URL
  private handleError(error: any): Promise {
    return Promise.reject(error.message || error);
  }
}

StackBlitz [1111 ]

9
задан Jeff Atwood 2 January 2009 в 10:45
поделиться

4 ответа

Как блок итератора:

using System;
using System.Collections.Generic;
using System.Linq;

static class Program {
    static IEnumerable<long> Fibonacci() {
        long n = 0, m = 1;

        yield return 0;
        yield return 1;
        while (true) {
            long tmp = n + m;
            n = m;
            m = tmp;
            yield return m;
        }
    }

    static void Main() {
        foreach (long i in Fibonacci().Take(10)) {
            Console.WriteLine(i);
        }
    }
}

Это теперь полностью лениво, и LINQ's использования Skip/Take и т.д. позволяет Вам управлять запущением/заканчиванием легко. Например, для Вашего "между" запросом:

foreach (long i in Fibonacci().SkipWhile(x=>x < from).TakeWhile(x=>x <= to)) {...}
45
ответ дан 4 December 2019 в 06:02
поделиться

Если Вы предпочитаете рекурсию вместо цикла:

public static void Main(string[] args)
{
    Func<int, int> fib = null;
    fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

    int start = 1;
    int end = 10;
    var numbers = Enumerable.Range(start, end).Select(fib);
    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }
}
4
ответ дан 4 December 2019 в 06:02
поделиться

Я изменился бы IEnumerable<int> введите к IEnumerable<Int64> поскольку это начнет переполняться от 50

2
ответ дан 4 December 2019 в 06:02
поделиться

Для тех, кто не привел Linq-редактору в подобном ко мне, 'Простому Jack' Версия. я ТАК запрещаюсь из клуба ;) джедая

static List<int> GetAllFibonacciNumbersUpto(int y)
{
   List<int> theFibonacciSeq = new List<int>();

   theFibonacciSeq.Add(0);   theFibonacciSeq.Add(1);

   int F_of_n_minus_2 = 0;   int F_of_n_minus_1 = 1;
   while (F_of_n_minus_2 <= y)
   {
      theFibonacciSeq.Add(F_of_n_minus_1 + F_of_n_minus_2);

      F_of_n_minus_2 = F_of_n_minus_1;
      F_of_n_minus_1 = theFibonacciSeq.Last<int>();
   }
   return theFibonacciSeq;
}

теперь, когда у нас есть это из пути...

// read in some limits
int x = 0; int y = 6785;

foreach (int iNumber in GetAllFibonacciNumbersUpto(y).FindAll(element => (element >= x) && (element <= y)))
    Console.Write(iNumber + ",");
Console.WriteLine();
-1
ответ дан 4 December 2019 в 06:02
поделиться
Другие вопросы по тегам:

Похожие вопросы: