Read More
Game simulations
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class KnightsTour {
public static void main(String[] args) {
// size of board
int N = 8;
// knight start position (x,y). x and y must be in range [0,N-1].
Position start = new Position(0,0);
// knight finish position (x,y). x and y must be in range [0,N-1].
Position finish = new Position(1,2);
// get search result from start to finish
List result = search(N, start, finish);
// if result is not empty -> output it
if( result != null ) {
System.out.println("Path is found:");
System.out.println(result.stream().map(Position::toString).collect(Collectors.joining(", ")));
}
// otherwise show message
else {
System.out.println("Path not found");
}
}
/**
* Method for searching knight full-tour path from start to finish
* @param n board size
* @param start position to start from
* @param finish position to finish on
* @return List of consecutive positions in target path
*/
private static Listsearch(int n, Position start, Position finish) {
// start and finish need to satisfy parity condition to make desired path available
if ((n*n + start.x + start.y + finish.x + finish.y) % 2 == 0)
return null;
// create initial path, started from 'start'
LinkedList path = new LinkedList<>();
path.add(start);
// two dimensional array for storing visited position
int[][] board = new int[n][n];
// mark started position as visited
board[start.x][start.y] = 1;
// starting dfs
// if result is true, path is found, return position list
if (dfs(n, finish, board, path))
return path;
// otherwise, path is not found, return null
return null;
}
/**
* DFS-step method for searching full tour path
* @param n board size
* @param finish target board position
* @param board array of flags, to mark visited positions
* @param path partial list of positions in final result path
* @return true, if path is found, false --- otherwise
*/
private static booleandfs(int n, Position finish, int[][] board, LinkedList path) {
// iterating over all possible moves
for (Position position : moves(path.getLast(), n)) {
// if possible move leads to visited position, skip it
if (board[position.x][position.y] == 1) {
continue;
}
// if possible move leads to finish position, checking number of steps:
if (position.equals(finish)) {
// if it is last unvisited position, add it to path and return true;
if (n*n - 1 == path.size()) {
path.add(position);
return true;
}
// otherwise --- skip it
continue;
}
// mark new position as visited
board[position.x][position.y] = 1;
// add it to path
path.add(position);
// try to make next step
boolean result = dfs(n, finish, board, path);
// if this position subsequently leads to correct path, return true
if (result) {
return true;
}
// otherwise, unmark position as visited, remove it from path
board[position.x][position.y] = 0;
path.removeLast();
}
// if no possible move leads to correct target path, return false
return false;
}
/**
* Return collection of possible moves
* @param from a position to make move from
* @param n board size
* @return collection of possible moves
*/
private static Listmoves(Position from, int n) {
List result = new ArrayList<>();
// for each possible knight move, check if it stays inside the board
if (from.x>= 2 &&from.y>= 1) {
result.add(new Position(from.x - 2, from.y - 1));
}
if (from.x>= 1 &&from.y>= 2) {
result.add(new Position(from.x - 1, from.y - 2));
}
if (from.x>= 2 &&from.y< n-1) {
result.add(new Position(from.x - 2, from.y + 1));
}
if (from.x>= 1 &&from.y< n-2) {
result.add(new Position(from.x - 1, from.y + 2));
}
if (from.x< n-1 &&from.y>= 2) {
result.add(new Position(from.x + 1, from.y - 2));
}
if (from.x< n-2 &&from.y>= 1) {
result.add(new Position(from.x + 2, from.y - 1));
}
if (from.x< n-1 &&from.y< n-2) {
result.add(new Position(from.x + 1, from.y + 2));
}
if (from.x< n-2 &&from.y< n-1) {
result.add(new Position(from.x + 2, from.y + 1));
}
return result;
}
/**
* Inner class, representing board position (cell)
*/
private static class Position {
int x;
int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
// Two positions are equal, if their x's and y's are equal respectively
@Override
public booleanequals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Position position = (Position) o;
return x == position.x&&
y == position.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
// String representation of position
@Override
public String toString() {
return MessageFormat.format("[{0},{1}]",x,y);
}
}
}
CSV String Manipulation
def replace_csv_entry(line, n, new_val):
"""csv line manipulation"""
data = line.split(',')
data[n-1] = str(new_val)
return ','.join(data)
def sum_csv(fname):
"""Sum of integers in a csv file"""
result = 0
try:
with open(fname, 'r') as f:
for line in f.readlines():
line = line.split(',')
result += sum(int(number) for number in line)
except FileNotFoundError as identifier:
pass
return result
def shuffle(fname):
"""Swap first and last line of a file"""
output_fname = 'shuffle_' + fname
lines = []
with open(fname, 'r') as f:
lines = [line.strip() for line in f.readlines()]
# Swap first and endline
lines[0], lines[-1] = lines[-1], lines[0]
with open(output_fname, 'w') as f:
for index, line in enumerate(lines):
endline = '\n'
# Last line won't have a return line.
if index == len(lines)-1:
endline = ''
f.write(line+endline)
if __name__ == "__main__":
# Sample execution
assert replace_csv_entry('45,2,52,2,10,4', 4, 75) == '45,2,52,75,10,4'
assert replace_csv_entry('98,87,54,43,21,32,54', 1, 6) == '6,87,54,43,21,32,54'
assert replace_csv_entry('50,60', 2, 100) == '50,100'
print('fakefile.csv sum %s' % sum_csv('fakefile.csv'))
print('test4.csv sum %s' % sum_csv('test4.csv'))
shuffle('pokemon.txt')