舌头算法的C++实现

      观察生活,我们不难发现,吃饭的时候,有时候左边的东西会到右边来,这是为什么呢?就是舌头的作用了。

     下面的代码将模拟舌头的运动:

#include <iostream>
#include <cstdlib> 
#include <time.h>
#define random(a,b) (rand()%(b-a+1))+a
using namespace std;
const int lenth = 5;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main() {
	int right[lenth] = {0};
	int middle[lenth] = {0};
	int left[lenth] = {0};
	
	srand(time(NULL));
	int temp[lenth+1] = {0};
	temp[0] = -1;
	int food = random(20,80);
	cout << "food" << " " << food << endl;
	for(int i = 0;;) {
		temp[i+1] = random(0,2);
		cout << "temp: " << temp[i] << endl;
		if(temp[i] == -1) {
			if(temp[i+1] == 0) {
				right[i] = food / 2;
			}
		    else if(temp[i+1] == 2) {
				left[i] = food / 2;
				
			}
			else if(temp[i+1] == 1) {
				middle[i] = food;
			}
			++i;
		}
		else if((temp[i+1] == 0) && (temp[i] != 2)) {
			if(temp[i] == 0) {
				right[i] = right[i-1] / 2;
				++i;
			}
			else if(temp[i] == 1){
				right[i] = middle[i-1] / 2;
				++i;
			}	
		}
		else if((temp[i+1] == 2) && (temp[i] != 0)) {
			if(temp[i] == 1) {
				left[i] = middle[i-1] / 2;
				++i;
			}
			else if(temp[i] == 2){
				left[i] = left[i-1] / 2;
				++i;
			}			
		}
		else if(temp[i+1] == 1){
			if(temp[i] == 0) {
				middle[i] = right[i-1];
				++i;
			}
			else if(temp[i] == 2){
		    	middle[i] = left[i-1];
		    	++i;
			}
			else {
				middle[i] = middle[i-1];
				++i;
			}		    
		}
		if(i >= lenth) {
			break;
		} 
	}
	for(int i = 0;i < lenth;++i) {
		cout << right[i] << " " << middle[i] << " " << left[i] << endl;
	}
	
	return 0;
}

  算法的主要思想是通过三个数列,right、middle和left模仿舌头的运动。程序会生成一个食物,食物遇到左边的牙齿或者右边的牙齿,都会减半,遇到舌头则不会。食物随机从左边、中间和右边进入口腔,然后随机变换位置,但是这里有一个规则,左右两边的食物不能立刻跳到对面,需要通过舌头,而通过舌头时食物是不会减半的。

      是不是很有趣!

posted on 2021-08-05 12:02  飞凤颖悟绝伦  阅读(57)  评论(0编辑  收藏  举报

导航