Skip to content

Instantly share code, notes, and snippets.

@segfo
Last active September 5, 2021 12:21
Show Gist options
  • Save segfo/7dc14e73d5a232bdab50449c4559fa8a to your computer and use it in GitHub Desktop.
Save segfo/7dc14e73d5a232bdab50449c4559fa8a to your computer and use it in GitHub Desktop.
イテレータのサンプル
use std::iter::Iterator;
struct FibonacciNumberGenerator {
n: [u128; 2],
}
impl FibonacciNumberGenerator {
fn new() -> Self {
FibonacciNumberGenerator { n: [0, 1] }
}
}
impl Iterator for FibonacciNumberGenerator {
type Item = u128;
fn next(&mut self) -> Option<Self::Item> {
// それぞれ1/2して足したらu128の1/2のMAX越える=1/2しなくても超えるのでNoneを返す。
if self.n[0] / 2 + self.n[1] / 2 < u128::MAX / 2 {
let n = self.n[0] + self.n[1];
self.n[0] = self.n[1];
self.n[1] = n;
Some(n)
} else {
None
}
}
}
fn main() {
let fib = FibonacciNumberGenerator::new();
for number in fib {
print!("{} ", number);
}
}
import java.util.Iterator;
class IteratorSample {
public static void main(String[ ] args) {
FibonacciNumberGenerator fib = new FibonacciNumberGenerator();
for(int n: fib){
System.out.println(n+" ");
}
}
}
class FibonacciNumberGenerator implements Iterable<Integer>,Iterator<Integer>{
int[] n = new int[2];
public FibonacciNumberGenerator(){
this.n[0]=0;
this.n[0]=1;
}
public Iterator<Integer> iterator() {
return this;
}
public boolean hasNext(){
if (this.n[0]/2 + this.n[1]/2 < Integer.MAX_VALUE/2){
return true;
}
return false;
}
public Integer next(){
int n = 0;
if (this.hasNext()){
n = this.n[0] + this.n[1];
this.n[0] = this.n[1];
this.n[1] = n;
}
return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment