一亩三分地论坛

 找回密码
 获取更多干货,去instant注册!

扫码关注一亩三分地公众号
查看: 489|回复: 3
收起左侧

homework4

[复制链接] |试试Instant~ |关注本帖
ilyak 发表于 2015-7-10 22:24:35 | 显示全部楼层 |阅读模式

[其他]CS61B #1 - 2015-06-01@UCB

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干货,去instant注册!

x
唔,大概就是练一下package和inheritance的一次作业
 楼主| ilyak 发表于 2015-7-10 22:26:36 | 显示全部楼层
package synthesizer;

public interface BoundedQueue{
        public int capacity();
        public int fillCount();

        public boolean isEmpty();
        public boolean isFull();

        public void enqueue(double x);
        public double dequeue();
        public double peak();

}


package synthesizer;


public abstract class AbstractBoundedQueue implements BoundedQueue{
  protected int fillCount;
  protected int capacity;

  @Override
  public int capacity(){
    return capacity;
  }

  @Override
  public int fillCount(){
    return fillCount;
  }

  @Override
  public boolean isEmpty(){
          if(fillCount==0) return true;
          return false;
  }

  @Override
  public boolean isFull(){
          if(fillCount==capacity) return true;
          return false;
  }

}


package synthesizer;
// Make sure to make this class a part of the synthesizer package
//package <package name>;

public class ArrayRingBuffer extends AbstractBoundedQueue {
  /* Index for the next dequeue or peek. */
  private int first;           
  /* Index for the next enqueue. */
  private int last;            
  /* Array for storing the buffer data. */
  private double[] rb;

  /** Create a new ArrayRingBuffer with the given capacity. */
  public ArrayRingBuffer(int capacity) {
    // TODO: Create new array with capacity elements.
    //       first, last, and fillCount should all be set to 0.
    //       this.capacity should be set appropriately. Note that the local variable
    //       here shadows the field we inherit from AbstractBoundedQueue.
    this.capacity=capacity;
    rb=new double[this.capacity];
    first=0;
    last=0;
    fillCount=0;
  }

  /** Adds x to the end of the ring buffer. If there is no room, then
    * throw new RuntimeException("Ring buffer overflow")
    */
  public void enqueue(double x) {
    // TODO: Enqueue the item. Don't forget to increase fillCount and update last.
    // is there room?

    if(isFull()){
      throw new RuntimeException("Ring buffer overflow");
    }

    rb[last]=x;
    fillCount++;
    last++;
    last= last % capacity;
  }

  /** Dequeue oldest item in the ring buffer. If the buffer is empty, then
    * throw new RuntimeException("Ring buffer underflow");
    */
  public double dequeue() {
    // TODO: Dequeue the first item. Don't forget to decrease fillCount and update first.
    if(isEmpty()){
      throw new RuntimeException("Ring buffer underflow");
    }

    double temp=rb[first];

    fillCount--;
    first++;
    first= first % capacity;

    return temp;
  }

  /** Return oldest item, but don't remove it. */
  public double peak() {
    // TODO: Return the first item. None of your instance variables should change.
    return rb[first];
  }

}

package synthesizer;
import org.junit.Test;
import static org.junit.Assert.*;

/** Tests the ArrayRingBuffer class.
*  @author Josh Hug
*/

public class TestArrayRingBuffer {
    @Test
    public void someTest() {
       synthesizer.ArrayRingBuffer arb = new synthesizer.ArrayRingBuffer(5);
       arb.enqueue(1);
       assertEquals(1,arb.peak(),0);

       arb.enqueue(3);
       assertEquals(1,arb.peak(),0);

       arb.dequeue();
       assertEquals(3,arb.peak(),0);

    }

    /** Calls tests for ArrayRingBuffer. */
  public static void main(String[] args) {
      jh61b.junit.textui.runClasses(TestArrayRingBuffer.class);
    }

}

// Make sure to make this class a part of the synthesizer package
//package <package name>;
package synthesizer;

//Make sure this class is public
public class GuitarString {
    /** Constants. Do not change. In case you're curious, the keyword final means
      * the values cannot be changed at runtime. We'll discuss this and other topics
      * in lecture on Friday. */
    private static final int SR = 44100;      // Sampling Rate
    private static final double DECAY = .996; // energy decay factor

    /* Buffer for storing sound data. */
    private BoundedQueue buffer;

    /* Create a guitar string of the given frequency.  */
    public GuitarString(double frequency) {
        // TODO: Create a buffer with capacity = SR / frequency. You'll need to
        //       cast the result of this divsion operation into an int. For better
        //       accuracy, use the Math.round() function before casting.
        //       Your buffer should be initially filled with zeros.
        int capacity=(int) Math.round(SR/frequency);
        buffer= new ArrayRingBuffer(capacity);
        while(!buffer.isFull()){
            buffer.enqueue(0);
        }

    }


    /* Pluck the guitar string by replacing the buffer with white noise. */
    public void pluck() {
        // TODO: Dequeue everything in the buffer, and replace it with random numbers
        //       between -0.5 and 0.5. You can get such a number by using:
        //       double r = Math.random() - 0.5;
        //
        //       Make sure that your random numbers are different from each other.
        while(!buffer.isEmpty()){
            buffer.dequeue();
        }

        while(!buffer.isFull()){
            double r = Math.random() - 0.5;
           // if(r!=buffer.last)
            buffer.enqueue(r);
        }

    }

    /* Advance the simulation one time step by performing one iteration of
     * the Karplus-Strong algorithm.
     */
    public void tic() {
        // TODO: Dequeue the front sample and enqueue a new sample that is
        //       the average of the two multiplied by the DECAY factor.
        //       Do not call StdAudio.play().
        double m=(buffer.dequeue()+buffer.peak())*0.5*DECAY;
        buffer.enqueue(m);
    }

    /* Return the double at the front of the buffer. */
    public double sample() {
        return buffer.peak();
    }

}

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

karte_polo 发表于 2015-7-10 23:16:12 | 显示全部楼层
package synthesizer;

interface BoundedQueue {
        int capacity();          // return size of the buffer
        int fillCount();         // return number of items currently in the buffer
        boolean isEmpty();       // is the buffer empty (fillCount equals zero)?
        boolean isFull();        // is the buffer full (fillCount is same as capacity)?
        void enqueue(double x);  // add item x to the end
        double dequeue();        // delete and return item from the front
        double peek();           // return (but do not delete) item from the front
}

package synthesizer;

public abstract class AbstractBoundedQueue implements BoundedQueue {
        protected int fillCount;
        protected int capacity;
        public int capacity(){
                return capacity;
        }
        public int fillCount(){
                return fillCount;
        }
        public boolean isEmpty(){
                return fillCount==0;
        }
        public boolean isFull(){
                return fillCount==capacity;
        }

}

package synthesizer;

public class ArrayRingBuffer extends AbstractBoundedQueue {
          /* Index for the next dequeue or peek. */
          private int first;           
          /* Index for the next enqueue. */
          private int last;            
          /* Array for storing the buffer data. */
          private double[] rb;

          /** Create a new ArrayRingBuffer with the given capacity. */
          public ArrayRingBuffer(int capacity) {
            // TODO: Create new array with capacity elements.
            //       first, last, and fillCount should all be set to 0.
            //       this.capacity should be set appropriately. Note that the local variable
            //       here shadows the field we inherit from AbstractBoundedQueue.
                  this.capacity = capacity;
                  first = last = fillCount = 0;
                  rb = new double[capacity];
          }

          /** Adds x to the end of the ring buffer. If there is no room, then
            * throw new RuntimeException("Ring buffer overflow")
            */
          public void enqueue(double x) {
            // TODO: Enqueue the item. Don't forget to increase fillCount and update last.
            // is there room?
                  if (!this.isFull()){
                          rb[last]=x;
                          last++;
                          if (last==capacity){
                                  last = 0;
                          }
                          fillCount++;
                  }else{
                          throw new RuntimeException("Error");
                  }
          }

          /** Dequeue oldest item in the ring buffer. If the buffer is empty, then
            * throw new RuntimeException("Ring buffer underflow");
            */
          public double dequeue() {
            // TODO: Dequeue the first item. Don't forget to decrease fillCount and update first.
                  if (!this.isEmpty()){
                          double v = rb[first];
                          first++;
                          if (first==capacity){
                                  first = 0;
                          }
                          fillCount--;
                          return v;
                  }else{
                          throw new RuntimeException("Error");
                  }
          }

          /** Return oldest item, but don't remove it. */
          public double peek() {
            // TODO: Return the first item. None of your instance variables should change.
                  return rb[first];
          }

        }

为了HARP和GUITAR,稍微修改了GUITARSTRING类的结构:增加MUSICSTRING 这个接口,ABSTRACTGUITARSTRING 改写成为ABSTRACTMUSICSTRING,然后HARP和GUITAR再继承该抽象类:

package synthesizer;

interface MusicString {
         public void pluck();
         public void tic();
         public double sample();
}

package synthesizer;

public abstract class AbstractMusicString implements MusicString {
        private static int SR = 44100;
        static double DECAY;
        BoundedQueue buffer;
       
        public AbstractMusicString(double frequency, double sizefactor) {
             // TODO: Create a buffer with capacity = SR / frequency. You'll need to
             //       cast the result of this divsion operation into an int. For better
             //       accuracy, use the Math.round() function before casting.
             //       Your buffer should be initially filled with zeros.
                 double capacity = SR/frequency*sizefactor;
                 buffer = new ArrayRingBuffer((int) Math.round(capacity));
                 while(!buffer.isFull()){
                         buffer.enqueue(0);
                 }
                 }
         
         
         /* Pluck the guitar string by replacing the buffer with white noise. */
         public void pluck() {
             // TODO: Dequeue everything in the buffer, and replace it with random numbers
             //       between -0.5 and 0.5. You can get such a number by using:
             //       double r = Math.random() - 0.5;
             //
             //       Make sure that your random numbers are different from each other.
                 double r;
                 for(int i =0;i<buffer.capacity();i++){
                         buffer.dequeue();
                         r = Math.random();
                         buffer.enqueue(r);
                 }         
         }         
         /* Return the double at the front of the buffer. */
         public double sample() {
             return buffer.peek();
         }
}

package synthesizer;

public abstract class Harp_Guitar extends AbstractMusicString {

public Harp_Guitar(double frequency,double sizefactor) {
         super(frequency,sizefactor);
         }  
/* Advance the simulation one time step by performing one iteration of
  * the Karplus-Strong algorithm.
  */
public void tic() {
         double num1 = buffer.dequeue();
         double newnum = (num1+buffer.peek())/2*DECAY;
         buffer.enqueue(newnum);
}
}

package synthesizer;

public class GuitarString extends Harp_Guitar {

/* Create a guitar string of the given frequency.  */
public GuitarString(double frequency) {
         super(frequency,1.0);
         DECAY = .996;
         }  
}

package synthesizer;

public class HarpString extends Harp_Guitar{
         /* Create a harp string of the given frequency.  */
         public HarpString(double frequency) {
                 super(frequency,2.0);
                 DECAY = -0.996;
                 }  
        }

DRUM 和PIANO没有写,不过也只需要继承ABSTRACTMUSICSTRING后重载相应方法即可

评分

1

查看全部评分

回复 支持 反对

使用道具 举报

HNAKXR 发表于 2016-2-12 13:00:56 | 显示全部楼层
回复 支持 反对

使用道具 举报

本版积分规则

请点这里访问我们的新网站:一亩三分地Instant.

Instant搜索更强大,不扣积分,内容组织的更好更整洁!目前仍在beta版本,努力完善中!反馈请点这里

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2016-12-4 02:03

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表