Yahoo Interview Question for Software Engineer / Developers






Comment hidden because of low score. Click to expand.
11
of 11 vote

An Linear Array can be used to represent the Snake and Ladder Game. Each index will tell us the position we have rolled dice for. say board.

and board[i]=i

Representing Snake & Ladder.
Say there is snake from which takes us from 10 to 3 then 

board[10]=3
similarly for Ladders.

Throw of Dice 

The throw of dice can be implemented by a function returning a random number between 1 and 6.

Game of Play.
we get evaluate the player position by checking the position the player has rolled for in the board i.e. say i am at 10 and by throw of dice returns 3 so I will check board[13] and the value will be final position.

- dmanasvi11 May 03, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

How i know snake from 10-3 and ladder too?
Is there is separate array needed for represent snake and ladder position?

- Preethi September 29, 2014 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

One int variable storing current position of user. Hash Table for snake such that key = Snake'Mouth and Value = Snake Tail. So if user_position == x and if (SnakeHT.get(x) != null) then user_position = SnakeHT.get(x). Similarly another hash table for Ladder. User everytime dices, a random Number [1 6] gets generated and x = x + Random_Number and the snake and ladder position is checked as descibed above

- anshulzunke September 17, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

techdive.in/java/snake-and-ladder-game

- shankar November 06, 2011 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Lets create simple structure and create the array of structure.

#define FinishNum 100;
int startNum = 1;

struct cell {
    int snake = NULL;
    int ladder = NULL;
};


int create_snake_ladder_game_board() {
     static struct cell cells[FinishNum];
     create_snakes(); //Create snakes in any random places and also create the num below the current num.
     create_ladders(); // Create ladder in any random places and also create the num to get the push in the game.
}


int throw_dice() {
   return (rand()%6)+1;
}

//Based on current position and the move, identify the position, u never know this may be snake bite or ladder up!
int make_a_move(int player1_curr_pos, int move){


}

int main() {

int player1;
int player1_curr_pos = 0;

create_snake_ladder_game_board();

while(1) {
   int move = throw_dice();
   player1_curr_pos = make_a_move(player1_curr_pos, move);
    
   if(player1_curr_pos >= FinishNum) {
       printf("Win ... Game Over!!!");
   }

   sleep(1);
}

}

- Anonymous October 12, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class GameBoard {

private static Scanner scanner = new Scanner(System.in);
private static Random random = new Random();
private static int noOfPlayers;
private static Map<Integer, Integer> ladderPositionMap = new HashMap<>();
private static Map<Integer, Integer> snakePositionMap = new HashMap<>();
private static Map<Integer, Player> playerMap = new HashMap<>();

public static void main(String[] args) {

constructSnakePostion();
constructLadderPostion();
noOfPlayers = setUpNoOfPlayers();
playGame();

}

private static void constructLadderPostion() {

ladderPositionMap.put(3, 16);
ladderPositionMap.put(5, 7);
ladderPositionMap.put(15, 25);
ladderPositionMap.put(18, 20);
ladderPositionMap.put(21, 32);

}

private static void constructSnakePostion() {

snakePositionMap.put(12, 2);
snakePositionMap.put(14, 11);
snakePositionMap.put(17, 4);
snakePositionMap.put(31, 19);
snakePositionMap.put(35, 22);

}

private static int setUpNoOfPlayers() {

System.out.println("Input the no of player...");
int noOfUsers = 0;

try {

noOfUsers = scanner.nextInt();

for (int i = 1; i <= noOfUsers; i++) {
Player player = new Player();
player.playerName = "Player: " + i;
playerMap.put(i, player);
}

} catch (Exception e) {
e.printStackTrace();
}

return noOfUsers;
}

private static void playGame() {

int currentPlayer = 1;

for (;;) {

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

scanner.nextLine();

System.out.println("Its Player: " + currentPlayer
+ " chance to play, Role the dice by pressing enter...");

Player player = playerMap.get(currentPlayer);
player.oldPosition = player.currentPosition;

scanner.nextLine();

int currentPosition = random.nextInt(6) + 1;

System.out.println(player.playerName + " has rolled no "
+ currentPosition + " in the dice");

player.currentPosition = player.oldPosition + currentPosition;

Integer newLadderPosition = checkIfLadderExists(player,
player.currentPosition);
Integer newSnakePosition = checkIfSnakeExists(player,
player.currentPosition);

if (newLadderPosition == null && newSnakePosition == null) {
System.out.println(player.playerName
+ " has moved from the position: " + player.oldPosition
+ " to position: " + player.currentPosition);
}

if (player.currentPosition >= 36) {
System.out.println(player.playerName
+ " has finished the game...");
break;
}

if (noOfPlayers == currentPlayer) {
currentPlayer = 1;
continue;
}

currentPlayer++;

}

}

private static Integer checkIfLadderExists(Player player,
int currentPosition) {

Integer newLadderPosition = ladderPositionMap.get(currentPosition);

if (newLadderPosition != null) {

player.currentPosition = newLadderPosition;
System.out.println(player.playerName + " has found a ladder: "
+ "at position: " + currentPosition
+ " hence moving up to a new position: "
+ player.currentPosition + " from position: "
+ currentPosition);

}

return newLadderPosition;
}

private static Integer checkIfSnakeExists(Player player, int currentPosition) {

Integer newSnakePosition = snakePositionMap.get(currentPosition);

if (newSnakePosition != null) {

player.currentPosition = newSnakePosition;
System.out.println(player.playerName + " has found a snake: "
+ "at position: " + currentPosition
+ " hence moving down to a new position: "
+ newSnakePosition + " from position: " + currentPosition);

}

return newSnakePosition;
}

}

- Anonymous July 07, 2015 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class GameBoard {

private static Scanner scanner = new Scanner(System.in);
private static Random random = new Random();
private static int noOfPlayers;
private static Map<Integer, Integer> ladderPositionMap = new HashMap<>();
private static Map<Integer, Integer> snakePositionMap = new HashMap<>();
private static Map<Integer, Player> playerMap = new HashMap<>();

public static void main(String[] args) {

constructSnakePostion();
constructLadderPostion();
noOfPlayers = setUpNoOfPlayers();
playGame();

}

private static void constructLadderPostion() {

ladderPositionMap.put(3, 16);
ladderPositionMap.put(5, 7);
ladderPositionMap.put(15, 25);
ladderPositionMap.put(18, 20);
ladderPositionMap.put(21, 32);

}

private static void constructSnakePostion() {

snakePositionMap.put(12, 2);
snakePositionMap.put(14, 11);
snakePositionMap.put(17, 4);
snakePositionMap.put(31, 19);
snakePositionMap.put(35, 22);

}

private static int setUpNoOfPlayers() {

System.out.println("Input the no of player...");
int noOfUsers = 0;

try {

noOfUsers = scanner.nextInt();

for (int i = 1; i <= noOfUsers; i++) {
Player player = new Player();
player.playerName = "Player: " + i;
playerMap.put(i, player);
}

} catch (Exception e) {
e.printStackTrace();
}

return noOfUsers;
}

private static void playGame() {

int currentPlayer = 1;

for (;;) {

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

scanner.nextLine();

System.out.println("Its Player: " + currentPlayer
+ " chance to play, Role the dice by pressing enter...");

Player player = playerMap.get(currentPlayer);
player.oldPosition = player.currentPosition;

scanner.nextLine();

int currentPosition = random.nextInt(6) + 1;

System.out.println(player.playerName + " has rolled no "
+ currentPosition + " in the dice");

player.currentPosition = player.oldPosition + currentPosition;

Integer newLadderPosition = checkIfLadderExists(player,
player.currentPosition);
Integer newSnakePosition = checkIfSnakeExists(player,
player.currentPosition);

if (newLadderPosition == null && newSnakePosition == null) {
System.out.println(player.playerName
+ " has moved from the position: " + player.oldPosition
+ " to position: " + player.currentPosition);
}

if (player.currentPosition >= 36) {
System.out.println(player.playerName
+ " has finished the game...");
break;
}

if (noOfPlayers == currentPlayer) {
currentPlayer = 1;
continue;
}

currentPlayer++;

}

}

private static Integer checkIfLadderExists(Player player,
int currentPosition) {

Integer newLadderPosition = ladderPositionMap.get(currentPosition);

if (newLadderPosition != null) {

player.currentPosition = newLadderPosition;
System.out.println(player.playerName + " has found a ladder: "
+ "at position: " + currentPosition
+ " hence moving up to a new position: "
+ player.currentPosition + " from position: "
+ currentPosition);

}

return newLadderPosition;
}

private static Integer checkIfSnakeExists(Player player, int currentPosition) {

Integer newSnakePosition = snakePositionMap.get(currentPosition);

if (newSnakePosition != null) {

player.currentPosition = newSnakePosition;
System.out.println(player.playerName + " has found a snake: "
+ "at position: " + currentPosition
+ " hence moving down to a new position: "
+ newSnakePosition + " from position: " + currentPosition);

}

return newSnakePosition;
}

}

- Sharan July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class GameBoard {

private static Scanner scanner = new Scanner(System.in);
private static Random random = new Random();
private static int noOfPlayers;
private static Map<Integer, Integer> ladderPositionMap = new HashMap<>();
private static Map<Integer, Integer> snakePositionMap = new HashMap<>();
private static Map<Integer, Player> playerMap = new HashMap<>();

public static void main(String[] args) {

constructSnakePostion();
constructLadderPostion();
noOfPlayers = setUpNoOfPlayers();
playGame();

}

private static void constructLadderPostion() {

ladderPositionMap.put(3, 16);
ladderPositionMap.put(5, 7);
ladderPositionMap.put(15, 25);
ladderPositionMap.put(18, 20);
ladderPositionMap.put(21, 32);

}

private static void constructSnakePostion() {

snakePositionMap.put(12, 2);
snakePositionMap.put(14, 11);
snakePositionMap.put(17, 4);
snakePositionMap.put(31, 19);
snakePositionMap.put(35, 22);

}

private static int setUpNoOfPlayers() {

System.out.println("Input the no of player...");
int noOfUsers = 0;

try {

noOfUsers = scanner.nextInt();

for (int i = 1; i <= noOfUsers; i++) {
Player player = new Player();
player.playerName = "Player: " + i;
playerMap.put(i, player);
}

} catch (Exception e) {
e.printStackTrace();
}

return noOfUsers;
}

private static void playGame() {

int currentPlayer = 1;

for (;;) {

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

scanner.nextLine();

System.out.println("Its Player: " + currentPlayer
+ " chance to play, Role the dice by pressing enter...");

Player player = playerMap.get(currentPlayer);
player.oldPosition = player.currentPosition;

scanner.nextLine();

int currentPosition = random.nextInt(6) + 1;

System.out.println(player.playerName + " has rolled no "
+ currentPosition + " in the dice");

player.currentPosition = player.oldPosition + currentPosition;

Integer newLadderPosition = checkIfLadderExists(player,
player.currentPosition);
Integer newSnakePosition = checkIfSnakeExists(player,
player.currentPosition);

if (newLadderPosition == null && newSnakePosition == null) {
System.out.println(player.playerName
+ " has moved from the position: " + player.oldPosition
+ " to position: " + player.currentPosition);
}

if (player.currentPosition >= 36) {
System.out.println(player.playerName
+ " has finished the game...");
break;
}

if (noOfPlayers == currentPlayer) {
currentPlayer = 1;
continue;
}

currentPlayer++;

}

}

private static Integer checkIfLadderExists(Player player,
int currentPosition) {

Integer newLadderPosition = ladderPositionMap.get(currentPosition);

if (newLadderPosition != null) {

player.currentPosition = newLadderPosition;
System.out.println(player.playerName + " has found a ladder: "
+ "at position: " + currentPosition
+ " hence moving up to a new position: "
+ player.currentPosition + " from position: "
+ currentPosition);

}

return newLadderPosition;
}

private static Integer checkIfSnakeExists(Player player, int currentPosition) {

Integer newSnakePosition = snakePositionMap.get(currentPosition);

if (newSnakePosition != null) {

player.currentPosition = newSnakePosition;
System.out.println(player.playerName + " has found a snake: "
+ "at position: " + currentPosition
+ " hence moving down to a new position: "
+ newSnakePosition + " from position: " + currentPosition);

}

return newSnakePosition;
}

}

- Sharan July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class GameBoard {

	private static Scanner scanner = new Scanner(System.in);
	private static Random random = new Random();
	private static int noOfPlayers;
	private static Map<Integer, Integer> ladderPositionMap = new HashMap<>();
	private static Map<Integer, Integer> snakePositionMap = new HashMap<>();
	private static Map<Integer, Player> playerMap = new HashMap<>();

	public static void main(String[] args) {

		constructSnakePostion();
		constructLadderPostion();
		noOfPlayers = setUpNoOfPlayers();
		playGame();

	}

	private static void constructLadderPostion() {

		ladderPositionMap.put(3, 16);
		ladderPositionMap.put(5, 7);
		ladderPositionMap.put(15, 25);
		ladderPositionMap.put(18, 20);
		ladderPositionMap.put(21, 32);

	}

	private static void constructSnakePostion() {

		snakePositionMap.put(12, 2);
		snakePositionMap.put(14, 11);
		snakePositionMap.put(17, 4);
		snakePositionMap.put(31, 19);
		snakePositionMap.put(35, 22);

	}

	private static int setUpNoOfPlayers() {

		System.out.println("Input the no of player...");
		int noOfUsers = 0;

		try {

			noOfUsers = scanner.nextInt();

			for (int i = 1; i <= noOfUsers; i++) {
				Player player = new Player();
				player.playerName = "Player: " + i;
				playerMap.put(i, player);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return noOfUsers;
	}

	private static void playGame() {

		int currentPlayer = 1;

		for (;;) {

			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			scanner.nextLine();

			System.out.println("Its Player: " + currentPlayer
					+ " chance to play, Role the dice by pressing enter...");

			Player player = playerMap.get(currentPlayer);
			player.oldPosition = player.currentPosition;

			scanner.nextLine();

			int currentPosition = random.nextInt(6) + 1;

			System.out.println(player.playerName + " has rolled no "
					+ currentPosition + " in the dice");

			player.currentPosition = player.oldPosition + currentPosition;

			Integer newLadderPosition = checkIfLadderExists(player,
					player.currentPosition);
			Integer newSnakePosition = checkIfSnakeExists(player,
					player.currentPosition);

			if (newLadderPosition == null && newSnakePosition == null) {
				System.out.println(player.playerName
						+ " has moved from the position: " + player.oldPosition
						+ " to position: " + player.currentPosition);
			}

			if (player.currentPosition >= 36) {
				System.out.println(player.playerName
						+ " has finished the game...");
				break;
			}

			if (noOfPlayers == currentPlayer) {
				currentPlayer = 1;
				continue;
			}

			currentPlayer++;

		}

	}

	private static Integer checkIfLadderExists(Player player,
			int currentPosition) {

		Integer newLadderPosition = ladderPositionMap.get(currentPosition);

		if (newLadderPosition != null) {

			player.currentPosition = newLadderPosition;
			System.out.println(player.playerName + " has found a ladder: "
					+ "at position: " + currentPosition
					+ " hence moving up to a new position: "
					+ player.currentPosition + " from position: "
					+ currentPosition);

		}

		return newLadderPosition;
	}

	private static Integer checkIfSnakeExists(Player player, int currentPosition) {

		Integer newSnakePosition = snakePositionMap.get(currentPosition);

		if (newSnakePosition != null) {

			player.currentPosition = newSnakePosition;
			System.out.println(player.playerName + " has found a snake: "
					+ "at position: " + currentPosition
					+ " hence moving down to a new position: "
					+ newSnakePosition + " from position: " + currentPosition);

		}

		return newSnakePosition;
	}

}

- Anonymous July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

xx

- xx July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

xx

- xx July 07, 2015 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Implement the Snakes and Ladder game


Base Assumptions

- Input can be read in from the terminal (UI not a must)

- Each player can play on the same terminal taking turns (NO network/multi-machine based logic required)


Required:

- Configurable board size

- Configurable number of players

- Configurable snake and ladder locations

- Rex June 02, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

can you send the logic for board logic for snake and ladder

- shekar June 03, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Assume we have a game. How to verify that it can be solved? i.e., how to prove that there is a solution?

- test July 08, 2016 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's python solution using linear array for board
{{

class Player:
def __init__(self, name):
self._name = name
self._position = 1

@property
def name(self):
return self._name

@property
def position(self):
return self._position

@position.setter
def position(self, position):
self._position = position


class Game:
BOARD_SIZE = 101
def __init__(self, players):
self.players = players
self.turn = 0
self.board = [0]*Game.BOARD_SIZE
self.winner = None

@property
def player_count(self):
return len(self.players)

def add_ladder(self, on, to):
if to < 0:
raise TypeError('to must be greater than 0')
self.board[on] = to

def add_snake(self, on, to):
if to > 0:
raise TypeError('to must be less than 0')
self.board[on] = to

def roll_dice(self, player=None):
if self.winner:
print 'game finished player %s won' % player.name
return
from random import randint
dice = randint(1, 6)
print 'dice rolled', dice
player = player or self.get_player_turn()
player.position += dice
if player.position >= Game.BOARD_SIZE:
self.winner = player
print(player.name, ' wins')
return
player.position += self.board[player.position]
if dice == 6:
print(player.name, 'turn again')
self.roll_dice(player)
self.print_positions_of_players()

def print_positions_of_players(self):
for player in self.players:
print '%s position: %s' % (player.name, player.position)

def get_player_turn(self):
player = self.players[self.turn]
self.turn += 1
if self.turn >= self.player_count:
self.turn = 0
return player


p1 = Player('ekluv')
p2 = Player('singh')

game = Game([p1, p2])
game.roll_dice()
game.roll_dice()
game.roll_dice()
game.roll_dice()

}}

- Ekluv Singh June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's python solution using linear array as board
{{class Player:
def __init__(self, name):
self._name = name
self._position = 1

@property
def name(self):
return self._name

@property
def position(self):
return self._position

@position.setter
def position(self, position):
self._position = position


class Game:
BOARD_SIZE = 101
def __init__(self, players):
self.players = players
self.turn = 0
self.board = [0]*Game.BOARD_SIZE
self.winner = None

@property
def player_count(self):
return len(self.players)

def add_ladder(self, on, to):
if to < 0:
raise TypeError('to must be greater than 0')
self.board[on] = to

def add_snake(self, on, to):
if to > 0:
raise TypeError('to must be less than 0')
self.board[on] = to

def roll_dice(self, player=None):
if self.winner:
print 'game finished player %s won' % player.name
return
from random import randint
dice = randint(1, 6)
print 'dice rolled', dice
player = player or self.get_player_turn()
player.position += dice
if player.position >= Game.BOARD_SIZE:
self.winner = player
print(player.name, ' wins')
return
player.position += self.board[player.position]
if dice == 6:
print(player.name, 'turn again')
self.roll_dice(player)
self.print_positions_of_players()

def print_positions_of_players(self):
for player in self.players:
print '%s position: %s' % (player.name, player.position)

def get_player_turn(self):
player = self.players[self.turn]
self.turn += 1
if self.turn >= self.player_count:
self.turn = 0
return player


p1 = Player('ekluv')
p2 = Player('singh')

game = Game([p1, p2])
game.roll_dice()
game.roll_dice()
game.roll_dice()
game.roll_dice()}}

- Ekluv Singh June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Here's python solution using linear array for board

class Player:
    def __init__(self, name):
        self._name = name
        self._position = 1
    
    @property
    def name(self):
        return self._name

    @property
    def position(self):
        return self._position

    @position.setter
    def position(self, position):
        self._position = position


class Game:
    BOARD_SIZE = 101
    def __init__(self, players):
        self.players = players
        self.turn = 0
        self.board = [0]*Game.BOARD_SIZE
        self.winner = None

    @property
    def player_count(self):
        return len(self.players)

    def add_ladder(self, on, to):
        if to < 0:
            raise TypeError('to must be greater than 0')
        self.board[on] = to

    def add_snake(self, on, to):
        if to > 0:
            raise TypeError('to must be less than 0')
        self.board[on] = to

    def roll_dice(self, player=None):
        if self.winner:
            print 'game finished player %s won' % player.name
            return
        from random import randint
        dice = randint(1, 6)
        print 'dice rolled', dice
        player = player or self.get_player_turn()
        player.position += dice
        if player.position >= Game.BOARD_SIZE:
            self.winner = player
            print(player.name, ' wins')
            return
        player.position +=  self.board[player.position]
        if dice == 6:
            print(player.name, 'turn again')
            self.roll_dice(player)
        self.print_positions_of_players()

    def print_positions_of_players(self):
        for player in self.players:
            print '%s position: %s' % (player.name, player.position)

    def get_player_turn(self):
        player = self.players[self.turn]
        self.turn += 1
        if self.turn >= self.player_count:
            self.turn = 0
        return player


p1 = Player('ekluv')
p2 = Player('singh')

game = Game([p1, p2])
game.roll_dice()
game.roll_dice()
game.roll_dice()
game.roll_dice()

- Ekluv Singh June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

class Player:
def __init__(self, name):
self._name = name
self._position = 1

@property
def name(self):
return self._name

@property
def position(self):
return self._position

@position.setter
def position(self, position):
self._position = position


class Game:
BOARD_SIZE = 101
def __init__(self, players):
self.players = players
self.turn = 0
self.board = [0]*Game.BOARD_SIZE
self.winner = None

@property
def player_count(self):
return len(self.players)

def add_ladder(self, on, to):
if to < 0:
raise TypeError('to must be greater than 0')
self.board[on] = to

def add_snake(self, on, to):
if to > 0:
raise TypeError('to must be less than 0')
self.board[on] = to

def roll_dice(self, player=None):
if self.winner:
print 'game finished player %s won' % player.name
return
from random import randint
dice = randint(1, 6)
print 'dice rolled', dice
player = player or self.get_player_turn()
player.position += dice
if player.position >= Game.BOARD_SIZE:
self.winner = player
print(player.name, ' wins')
return
player.position += self.board[player.position]
if dice == 6:
print(player.name, 'turn again')
self.roll_dice(player)
self.print_positions_of_players()

def print_positions_of_players(self):
for player in self.players:
print '%s position: %s' % (player.name, player.position)

def get_player_turn(self):
player = self.players[self.turn]
self.turn += 1
if self.turn >= self.player_count:
self.turn = 0
return player


p1 = Player('ekluv')
p2 = Player('singh')

game = Game([p1, p2])
game.roll_dice()
game.roll_dice()
game.roll_dice()
game.roll_dice()

- Ekluv Singh June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

asdasd

- asd June 18, 2017 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

package javaapplication3;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;


public class JavaApplication3 {
    private static class Player{
        String playerName;
        int oldPosition;
        int currentPosition;
    }
    private static Scanner scanner = new Scanner(System.in);
	private static Random random = new Random();
	private static int noOfPlayers;
	private static Map<Integer, Integer> ladderPositionMap = new HashMap<>();
	private static Map<Integer, Integer> snakePositionMap = new HashMap<>();
	private static Map<Integer, Player> playerMap = new HashMap<>();

	public static void main(String[] args) {

		constructSnakePostion();
		constructLadderPostion();
		noOfPlayers = setUpNoOfPlayers();
		playGame();

	}

	private static void constructLadderPostion() {

		ladderPositionMap.put(3, 16);
		ladderPositionMap.put(5, 7);
		ladderPositionMap.put(15, 25);
		ladderPositionMap.put(18, 20);
		ladderPositionMap.put(21, 32);

	}

	private static void constructSnakePostion() {

		snakePositionMap.put(12, 2);
		snakePositionMap.put(14, 11);
		snakePositionMap.put(17, 4);
		snakePositionMap.put(31, 19);
		snakePositionMap.put(35, 22);

	}

	private static int setUpNoOfPlayers() {

		System.out.println("Input the no of player...");
		int noOfUsers = 0;

		try {

			noOfUsers = scanner.nextInt();

			for (int i = 1; i <= noOfUsers; i++) {
				Player player = new Player();
				player.playerName = "Player: " + i;
				playerMap.put(i, player);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return noOfUsers;
	}

	private static void playGame() {

		int currentPlayer = 1;

		while(true) {

			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			//scanner.nextLine();

			System.out.println("Its Player: " + currentPlayer
					+ " chance to play, Role the dice by pressing enter...");

			Player player = playerMap.get(currentPlayer);
			player.oldPosition = player.currentPosition;

			//scanner.nextLine();

			int currentPosition = random.nextInt(6) + 1;

			System.out.println(player.playerName + " has rolled no "
					+ currentPosition + " in the dice");

			player.currentPosition = player.oldPosition + currentPosition;

			Integer newLadderPosition = checkIfLadderExists(player,
					player.currentPosition);
			Integer newSnakePosition = checkIfSnakeExists(player,
					player.currentPosition);

			if (newLadderPosition == null && newSnakePosition == null) {
				System.out.println(player.playerName
						+ " has moved from the position: " + player.oldPosition
						+ " to position: " + player.currentPosition);
			}

			if (player.currentPosition >= 36) {
				System.out.println(player.playerName
						+ " has finished the game...");
				break;
			}

			if (noOfPlayers == currentPlayer) {
				currentPlayer = 1;
				continue;
			}

			currentPlayer++;

		}

	}

	private static Integer checkIfLadderExists(Player player,
			int currentPosition) {

		Integer newLadderPosition = ladderPositionMap.get(currentPosition);

		if (newLadderPosition != null) {

			player.currentPosition = newLadderPosition;
			System.out.println(player.playerName + " has found a ladder: "
					+ "at position: " + currentPosition
					+ " hence moving up to a new position: "
					+ player.currentPosition + " from position: "
					+ currentPosition);

		}

		return newLadderPosition;
	}

	private static Integer checkIfSnakeExists(Player player, int currentPosition) {

		Integer newSnakePosition = snakePositionMap.get(currentPosition);

		if (newSnakePosition != null) {

			player.currentPosition = newSnakePosition;
			System.out.println(player.playerName + " has found a snake: "
					+ "at position: " + currentPosition
					+ " hence moving down to a new position: "
					+ newSnakePosition + " from position: " + currentPosition);

		}

		return newSnakePosition;
	}

    
    
}

- sachin12kumar007 August 22, 2017 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More