華爲機試—擲骰子游戲

在擲骰子游戲中,會根據所擲數字在地圖中前進幾步,前進完成後需要根據當前地圖位置所示的障礙進行相應操作,其中障礙表示:
1)9:無障礙
2)1:停擲一輪,即下輪所擲數字無效;
3)2:後退兩步,如果已經到起點不再後退;
4)3:獎勵前進一步

如果在遊戲過程中,已經走到地圖終點,則遊戲結束。根據輸入的地圖數組,和5個骰子數的數組,返回最終玩家前進了多少步。

示例
1)輸入:map_len = 15, map = {9,1,9,9,9,2,9,9,9,9,9,9,9,9,9},dice_val = {1,2,1,3,1},
返回:4
2)輸入:map_len = 16, map = {9,9,9,9,9,1,9,3,9,9,2,9,9,9,9,9},dice_val = {2,1,4,1,6},
返回:15

#include <stdio.h>

void dice(int map_len, int* map, int* dice_val, int* output)
{
    int step=0, i;
    for(i=0; i<5; i++)
    {
        step = step + dice_val[i];
        if(step>=map_len - 1)
        {
            step = map_len - 1;
            break;
        }
        else if(map[step] == 1)
            i++;
        else if(map[step] == 2)
        {
            if(step>1)
                step = step - 2;
            else
                step = 0;
        }
        else if(map[step] == 3)
            step++;
    }
    *output = step;
    printf("the output is %d\n",*output);
}

int main()
{
    int map_len = 15,  map[] = {9,1,9,9,9,2,9,9,9,9,9,9,9,9,9},  dice_val[] = {1,2,1,3,1};//4
    //int a=0 , * output=&a;
    int output[1];
    dice(map_len, map,  dice_val,  output);

    int map_len1 = 16,  map1[] = {9,9,9,9,9,1,9,3,9,9,2,9,9,9,9,9}, dice_val1[] = {2,1,4,1,6};//15
    //int a1=0 , * output1=&a1;
    int output1[1];
    dice(map_len1, map1,  dice_val1,  output1);

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章