Technical Inteview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Implement pow with Double pow(double x, double power) No library functions allowed Should return: x^power

#include <limits> #include <utility> #include <algorithm> #include <iostream> #include <cmath> /* That's the story (took roughly more than 45 minutes...) result = base ^ exponent, where the exponent is double (meaning e.g. 2.14 ^ 10.1241 or -2.14 ^ -1.42 which is a complex number) I can't cover all the special cases, such as -inf + inf, NaN, negative base and negative exponent, so I just assume base and exponent are positivie... it's complicated enough 1) if the exponent is an integer it's easy base^8 = ((base^2)^2)^2 (note 3 instead 8 multiplications, roughly lg(exp) multiplications 2) if the exponent has a decimal part e.g. base^8.5 we can write: base^(8+1/2) = base^8 * base^(1/2) (base^1/2 is the square-root of base, base^1/4 is the 4-th root of base etc...) so after powering the integer part, we multiply it with the power of the decimal part. powering the decimal part rquires us to have a root. root can be self-made by using newton method. newton method requires a good guess to converge and to not take long. a good guess can be done using binary search in the number range. note we can write the decimal part of the power as base^dec_exponent = base^0.33333 (e.g.) which is base^(0.25 + 0.0625 + 0.015625 + ...) which is base^(1/4 + 1/16 + 1/64) */ // power with integer exponent double mypow(double base, unsigned int exp) { if (exp == 0) return 1; if (exp == 1) return base; if (exp == 2) return base*base; double result = mypow(base, static_cast<unsigned int>(exp / 2)); result *= result; if (exp % 2 == 1) result *= base; return result; } // takes the square root based on binary search (could use newton method, too) double mysqrt(double value) { if (value == 0) return value; // guess x using "binary search" to get close double lo = 0.0; // root of something never get's below 0 double hi = value; double x = (hi + lo) / 2; while (abs(hi - lo) > 0.001) { x = (hi + lo) / 2; double res = x * x; if (res > value) hi = x; else lo = x; } // with the reasonable accurate guess perform newton methode for(int i = 0; i < 20; i++) { x = x - ((x*x - value) / (2 * x)); } return x; } // powerfunction as desired by the question double mypow(double base, double exp) { if ((exp < 0) && (base < 0) && (exp - static_cast<int>(exp) > 0.0)) throw "no support for complex numbers"; if (exp < 0) return 1.0 / mypow(base, -exp); // negative exponent is just 1/pow(base, -exp) double result = mypow(base, static_cast<unsigned int>(exp)); // power integer part double expdec = exp - static_cast<unsigned int>(exp); // remove integer part from exponent: 0 <= expdec < 1 if (expdec >= 1.0) throw "exponent too high"; if (expdec > 0.0) { double epsilon = 0.000000000000001; double currentRs = 1.0; double currentRt = mysqrt(base); double currentExp = 0.5; double remainingExp = expdec; while (remainingExp > epsilon && currentExp > epsilon) { if (remainingExp >= currentExp) { currentRs *= currentRt; remainingExp -= currentExp; } currentRt = mysqrt(currentRt); currentExp /= 2; } result *= currentRs; } return result; } // test helper function void testMyPow(double base, double exp) { double myresult = mypow(base, exp); double result = pow(base, exp); double error = abs(myresult - result); std::cout << "tested " << base << "^" << exp << " mypow returned " << myresult << " pow returned " << result << " error " << error << std::endl; } int main() { testMyPow(2.0, 20.0); testMyPow(2.0, -5.0); testMyPow(2, 1.5); testMyPow(0.212, 91.231); testMyPow(891.212, 0.33333333333); return 0; /* output tested 2^20 mypow returned 1.04858e+06 pow returned 1.04858e+06 error 0 tested 2^-5 mypow returned 0.03125 pow returned 0.03125 error 0 tested 2^1.5 mypow returned 2.82843 pow returned 2.82843 error 0 tested 0.212^91.231 mypow returned 3.47494e-62 pow returned 3.47494e-62 error 2.59085e-77 tested 891.212^0.333333 mypow returned 9.62337 pow returned 9.62337 error 3.55271e-15 */ }

Write a method to return the nth entry in the Fibonacci sequence

#include<stdio.h> int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main () { int n = 9; printf("%d", fib(n)); getchar(); return 0; }

You have a matrix that is sorted as such: For each value, every index to its right and below it must be larger than the current space's value. Likewise, all entries to its left and above it must be smaller than the current value. How would you go about searching this matrix for a specific number, given its sorted nature

1) Start with top right element 2) Loop: compare this element e with x ....i) if they are equal then return its position ...ii) e < x then move it to down (if out of bound of matrix then break return false) ..iii) e > x then move it to left (if out of bound of matrix then break return false) 3) repeat the i), ii) and iii) till you find element or returned false Implementation: #include<stdio.h> /* Searches the element x in mat[][]. If the element is found, then prints its position and returns true, otherwise prints "not found" and returns false */ int search(int mat[4][4], int n, int x) { int i = 0, j = n-1; //set indexes for top right element while ( i < n && j >= 0 ) { if ( mat[i][j] == x ) { printf("\n Found at %d, %d", i, j); return 1; } if ( mat[i][j] > x ) j--; else // if mat[i][j] < x i++; } printf("\n Element not found"); return 0; // if ( i==n || j== -1 ) } // driver program to test above function int main() { int mat[4][4] = { {10, 20, 30, 40}, {15, 25, 35, 45}, {27, 29, 37, 48}, {32, 33, 39, 50}, }; search(mat, 4, 29); getchar(); return 0; } Run on IDE Time Complexity: O(n) The above approach will also work for m x n matrix (not only for n x n). Complexity would be O(m + n).

Given 3 strings "s" "ssearch" and "sreplace", string search s for the substring ssearch for every instance of ssearch you find, replace that part of the string with sreplace

function module.exports = function (S, s, r) { var regex = new RegExp(s, 'g') return S.replace(regex, r) } You could use KMP to search "s" in "ssearch" and keep your new string in an efficient structure like StringBuilder if you're using Java

You have a group of pigs and buckets for food for said pigs. There are 1000 buckets of food, and exactly 1 of them is poisoned. Your goal is to determine, by the end of 1 hour, which bucket is poisoned. The poison takes 30 minutes to kill a pig, and you'd like to kill as few pigs as possible. The number of pigs you can test is limitless and you can assign a number to each bucket and each pig so that you know exactly which pig ate from which bucket(s). You determine which buckets to feed to which pigs, but you have no timer and no way to guesstimate the time. What is the minimum number of pigs you need to solve this problem.

9, he extends the binary-based answer to an n-dimensional matrix, by which you need 9 vectors of intersection to identify buckets by a unique combination of numbered pigs. 9 not 10 because you get 2 round in which to test for poison, 2 30 minute intervals, it is enough to decide 500 buckets at a time, which can be done with 9 pigs 7. If you only had 30 minutes, you could only go through once, and than you would be using binary coding to solve it like many people describe. But since you have 2 rounds, you could use ternary coding, because you can play with 3 states: pig dies after 1st round, pig dies after 2nd round, pig lives. With the first pig checking buckets 1-4-7-etc (10, 11, 12) the first round and 2-5-8 (20, 21, 22) the second round, the second pig checking 3-4-5-10-11-12-etc (010, 110, 210, 011, 111, 211) the first round and 6-7-8-13-14-15 the second round. 3^6 states is 729, not quite enough to rule out all the water, while 3^7 is 2187

Exception

A problem that arises during the execution of a program. found using try catch throw

Explain a factory method pattern

Abstract Factory Pattern: create instances of classes belonging to different families. The abstract factory class defines the abstract methods that have to be implemented by concrete factory classes. It serves as interface and contract definition. The concrete factory classes contain the real implementation that define which classes are created during run-time.

What is an abstract class? Why would you use it?

Abstract class may of may not include abstract methods. Abstract classes cannot be instantiated but they can be subclassed

Convert an unordered tree to a binary tree

Answer

Design a function for determining hits in battleship

Answer

Do you see a real problem with the modified 'order of'?

Answer

Do you think O(f) is a good idea for real engineering?

Answer

Explain forms of testing you would do before releasing software

Answer

Explain how a web request works in as much detail as possible

Answer

Given N weights, one of which is different from the others, find this different weight

Answer

Given a collection of songs with names and times, determine the longest mixtape you can make that fits into a CD that can hold 20 minutes of content

Answer

Merge two binary search trees

Answer

String replace all symbols with spaces

Answer

Tell me something about the project you love the most

Answer

Write a function that takes a linked list ordered as a normal link list, while also having an alternate order (alternate_next ptr for each), and copies it, preserving it's normal order as well as it's alternate order

Answer

You are given a function getNum() that returns a random number in the range from 1 to 10 million with repetitions. However, it may also return -1 when it no longer provides numbers. Write a function that calls getNum() continuously until it returns -1 (if a repetition, should not store it); as soon as u see -1, stop calling getNum() and print all the numbers seen so far in a sorted way. Condition: you have got very limited memory to work with

BitArray store = new BitArray(10000000, false); int num = GetNum(); while (num != -1) { if (!store.Get(num - 1)) store.Set(num - 1, true); num = GetNum(); } for (int i = 0; i < store.Length; i++) { if (store.Get(i)) Console.WriteLine(i + 1); }

C

C is procedural and doesn't support classes and objects

: If you were to sort 1 trillion unicode characters, what sorting method would you have used?

Counting soft because of small set of different unicode chars

How do you protect variables from accidental assignment

Declare it as a const

You are given an array of positive and negative integers. If a number n at an index is positive, then move forward n steps. Conversely, if it's negative move backward n steps. Determine if there is a loop in this array. For example, given the array [2, -1, 1, 2, 2], index 0 maps to 2, 1 maps to 0, 2 maps to 3, and so on. There is a loop in this array because 0 maps to 2, 2 maps to 3, and 3 maps to 0 (using modulo operator)

Every element of this array have "next" element to go (including itself). So we can do "next" starting from any element infinite times and always can continue. Thus EVERY possible array will have loop because array is finite. Loop length could be from 0 to N (whole array). static boolean cyclesThroughStart(int start, int... arr) { int slowIdx = start; int fastIdx = start; do { slowIdx = f(arr,slowIdx); fastIdx = f(arr,f(arr,fastIdx)); if (slowIdx == start || fastIdx == start) { return true; } } while(slowIdx != fastIdx); return false; } static int f(int[] arr,int idx) { idx += arr[idx]; return Math.abs(idx % arr.length); }

Interface

Every single method declared in an interface will have to be implemented in the subclass.

What are the two parts of recursion

Recursive step (gets smaller and smaller (n-1)) and the base case (factorial example)

What's the difference between the heap and the stack

Stack is used for static memory allocation and the heap for dynamic memory allocation. Stack

Assume that you are given the head and tail pointers of a doubly linked list where each node can also have a single child pointer to another similar doubly linked list. There are no cycles in this structure outside of the traditional double links. Write a procedure in C++ that flattens this structure into a single list.

I found out later that this problem is one of several classic programming questions taken from an interview book. Such a list has an obvious recursive structure, but it is large and so recursion is not practical. Consequently, an iterative approach is necessary. The invariant for such an approach maintains the flat list to the "left" and the possibly fat list to the "right." The PseudoCode solution mentioned above is *NOT* the desired answer because it involves recursion. As mentioned in the first comment, recursion is not allowed due to the very large structure of this list. The correct solution makes use of loop invariants.

If you had to create a system composed of two components, where one component is the primary component for running an application and the other is the backup component that only activates when the primary system malfunctions, how would you setup the system

In the primary system I would set up some sort of error detection or exception handling and that would cause a flag to go up that would indicate that the backup component needed to take over

If you were to sort 10 elements, what sorting method would you have used?

Insertion Sofrt

What is the advantage of a binary search over a hash table

Tree where left node is less and right node is greater. Hash left is zero, right is one, concatenating with parent node. Hash supports search, insert, and delete. Advantages of BST is you can get all the key in a sorted order by just traversing through the table which can't be done in a hash table. Sorting is easier with BST. Easier to implement. BST O(logn) H O(1) which can be costly.

Overloading vs overriding

Overloading occurs when two or more methods in one class have the same method name but different parameters. Overriding means having two methods with the same method name and parameters but one of the methods is in the parent class and the other is in the child class

Inserts a value into a sorted linked list Using C/C++ write a small function (around 5 lines of the body) to insert a value in a sorted linked list. Take into consideration that the list might be empty at first, and the function should cover the cases of insertion at the head and tail PS what the interviewer is looking for is the ability to write a small C/C++ code that solves the questions and not the algorithm per se which is trivial

Pay attention how the insert method is simple and concise #include <iostream> using namespace std; struct Node{ int value; Node* next; Node(int v){ value = v;} } *pHead; // the trick is in having a pointer to a pointer to a Node // this will allow to scan the linked list using one variable p // and insert on the head without any checking because every Node** p // represents all pointers (including the pHead variable) // all the algorithm is written in just 5 lines of code void insert (int v){ Node** p = &pHead; while(*p != NULL && v > (*p)->value) p = &(*p)->next; Node* n = new Node(v); n->next = *p; *p = n; } void display(){ Node* p = pHead; while (p != NULL){ cout << p->value << ", "; p = p->next; } } int main() { pHead = NULL; int array[] = {10, 5, 18, 40, 20, 15, 25, 0, 100, 50}; for(int i = 0; i < 10; i++ ){ insert(array[i]); } display(); return 0; } The output is: 0, 5, 10, 15, 18, 20, 25, 40, 50, 100

What would happen if you put objects in a stack past its limit

Program will crash

If I say quick sort takes O(e^n) on the average, would I be wrong?

Qsort complexity (worst of average) blong to class of functions O(e^n). Simply by definition of that class. In other words Big O notation means "grow asymptotically no faster than..."

Write a procedure in C that reverses the letters of a null-terminated string. Then write another procedure in C that reverses the words of a null-terminated sentence.

There are answers that are space optimal (e.g., reverse the words of a sentence by reversing the letters of a sentence and then reversing the letters of each word in place) and other answers that are time optimal (e.g., copy data into new data structures with the desired properties). This apparently is also another classic programming interview question.

Explain UML design

Unified modeling language. A way of visualizing software programs using diagrams. Used to define hierarchies or

Given an NxN boolean matrix, find how many true regions there are in the matrix

can be done using union-find data structure with one pass on the matrix. time: O(log*(NxN)) /** * Given an `N`x`N` Boolean matrix, find how many true * regions there are in the matrix. */ // Define a `true region` as any contiguous set of // true elements such that the true elements are // touching either horizontally, vertically, or // diagonally. // For each `i`,`j` element in the matrix, if it is // `true` mark it as "unvisited" and put it in the // search set. // Set `r` to be 0, the number of unique regions. // While there are elements in the search set, // take an element from the search set, if it // is "visited", discard it, if it is "unvisited" // mark it as "visited", and put it in the // working set and increment `r`. // While there are elements in the working set, // take the next element from the working set, // if it has any `true` neighbors among it's // 8 possible neighbors, mark those neighbors // as "visited" and add them to the working // set. // Return `r` the number of contiguous true regions of // the `N`x`N` matrix.

Sort a stack using only one other stack and no recursion

class Program { // Total array size. const int ARRAY_SIZE = 10; static void Main(string[] args) { Stack provided = new Stack(); provided.Push(4); provided.Push(7); provided.Push(2); provided.Push(1); provided.Push(3); provided.Push(10); provided.Push(6); provided.Push(3); provided.Push(18); provided.Push(13); // Sort the stack using another stack. SortStack(provided); // print the sorted start:- Console.WriteLine("Sorted Stack:"); while (provided.Top > -1) { provided.Pop(); } } /// <summary> /// Method to sort the stack. /// </summary> /// <param name="provided">array to be sorted.</param> static void SortStack(Stack provided) { // using one stack. Stack useThis = new Stack(); int val1, val2; // This method will sort the given stack from two ends. for (int i = 0; i < ARRAY_SIZE / 2; i++) { // PHASE 1: Shift larger number to an end, val1 = provided.Pop(); val2 = provided.Pop(); // get the largest at the top while (provided.Top > -1) { if (val1 < val2) { useThis.Push(val1); val1 = provided.Pop(); } else { useThis.Push(val2); val2 = provided.Pop(); } } if (val1 < val2) { useThis.Push(val1); useThis.Push(val2); } else { useThis.Push(val2); useThis.Push(val1); } // PHASE 2: Shift smaller number to another end. val1 = useThis.Pop(); val2 = useThis.Pop(); // get the smallest at the bottom while (useThis.Top > -1) { if (val1 < val2) { provided.Push(val2); val2 = useThis.Pop(); } else { provided.Push(val1); val1 = useThis.Pop(); } } if (val1 < val2) { provided.Push(val2); provided.Push(val1); } else { provided.Push(val1); provided.Push(val2); } } } } public class Stack { public Stack() { Top = -1; } // Total array size. const int ARRAY_SIZE = 10; // to track the top of stack. public int Top { get; set; } private int[] StackItems = new int[ARRAY_SIZE]; /// <summary> /// Push the given value in the given stack index. /// </summary> /// <param name="data">value to push</param> public void Push(int data) { if (Top < ARRAY_SIZE - 1) { StackItems[++Top] = data; } else { Console.Write("Stack Overflow"); throw new Exception("Stack Overflow"); } } /// <summary> /// Pop the items from the stack /// </summary> /// <returns>value poped from the stack</returns> public int Pop() { if (Top > -1) { Console.WriteLine("Item Pop: " + StackItems[Top]); return StackItems[Top--]; } else { Console.Write("Empty Stack"); throw new Exception("Empty Stack"); } } }

Given a dictionary and a char array print all the valid words that are possible using char from the array Ex- char[] arr = {'e','o','b', 'a','m','g', 'l'} Dict - {"go","bat","me","eat","goal", "boy", "run"} Print - go, me, goal. We can pre-compute as much we want but the query time must be optimal.

function valid (chars, dict) { var spellables = [] for (var j = 0; j < dict.length; ++j) { var map = {} for (var i = 0; i < chars.length; ++i) { if (map[chars[i]]) { map[chars[i]] += 1 } else { map[chars[i]] = 1 } } var bool = true for (var k = 0; k < dict[j].length; ++k) { if (!map[dict[j].charAt(k)]) { bool = false break } else { map[dict[j].charAt(k)]-- } } if (bool) { spellables.push(dict[j]) } } console.log(spellables) } valid(['e', 'o', 'b', 'a', 'm', 'g', 'l'], [ 'go', 'bat', 'me', 'eat', 'goal', 'boy', 'run' ]);

In the game of Jack Straws, a number of plastic straws are dumped on the table and players try to remove them one-by-one without disturbing the other straws. In the questions here, we are concerned with the following related problem: First n straws are dumped on the table. Next for every pair of straws, we want to determine if the straws are connected by a path of touching straws. In other words, given a list of endpoints for n > 1 straws (as if they were dumped on a large piece of graph paper). Determine all the pairs of straws that are connected. Note that touching is connecting, but also two straws can be connected indirectly via other connected straws. Give an algorithm to compute all the pairs of straws that are connected As a basic step you need to determine whether two straws directly touch (intersect) i.e. whether straw ab with endpoints a and b intersects with straw cd (endpoints c and d) To get full credit also explain how the elementary step i) can be done. If you cannot find an algorithm for this step, assume an O(n2) algorithm and explain how to find all pairs of straws that are connected. Analyse and explain the worst-case computational complexity of your algorithm in terms of n

how about getting all connected componrnts in the graph; run dtfs to get all connected componnents every pair of straws in a connected component is connected Develop an algorithm to find if two given line segments intersect Given 2 points find y2-y1 m1 = ...... x2 - x1 now line can be y = mx + b You get such equations for each line. Subtract both equations to get y and x of intersection. To do that make sure X is within min or Right X and Max of left X. Likewise make sure that Y is within max of bottom Y and min of top Y Well above two steps tell you whether two lines intersect of not, now lets build the solution for game using it A: Here is what i think of a solution for this problem First we define the structure of a straw. Class Straw { int X_1, Y_1;// this is to repersent first coordinate of the straw int X_2,Y_2;//secon coordinate } Now we are given N list of straws as input. Lets first define how two straw are connected to each other or not(we can consider this problem as to figure out whether two lines of 2D are intersecting/touching each or or not). We are use the Cross product to figure out this. bool IsIntersect(Straw a, Straw b) Define P1 = (a.X_1,a.Y_1);P2 = (a.X_2,a.Y_2); P3 = (b.X_1,b.Y_1);P4 = (b.X_2,b.Y_2); we can use following cross products to figure out whether these two straws intersecting/touching each other or not If Cross_Product(P1P2, P1P4) and Cross_Product(P1P2,P1P3) are apposite to each other and Cross_Product(P3P4, P3P1) and Cross_Product(P3P4,P3P2) are also apposite to each other then these two straws are intersecting, other wise if any of the cross_product is zero, which is the case when these two straws are touching each other or are their in a single line, then we just check the vertices of other lines, if any one of thems((p1 or p2) or (p3 or p4))'s x and y coordinate lies between other line's coordinetes. Now we will start the actual execution. We will keep three array of indexes, one which will have indexes straws in non decreasing order x coordinate other two will have non decreasing order of y coordinate of first and second vertices. now we will figure out the connected component. Please note that any straw from one connected component will only touch/intersect other straws of the same component. Here is the algorithm A <- Input straws Index_x <- indexes in nondecreasing order of min of x(from both the vertices of a straw) Index_y_1 <- indexes in nondecreasing order of y_1 Index_y_2 <- indexes in nondecreasing order of y_2 In index_x, we also keep one flag to tell whether something is left to try or not keep a queue Q = empty(normal queue) while(something left in index_x to try) take the first untried index, call it j, set tried flag to true; figure out the list of straws which may intersect/touch with straw j We can figure out by first figure out the list of untried straws using index_x, where index_x's straw's min x <= j' straws max x. then we will also figure out the list of untried straws using index_y_1 and index_y_2.where ay straws whose either first y coordinate or second y coordinate lies between J's straws min y and max y coordinate. we will put all these straws in the Q while(Q is not empty) straw_k <- Dequeue(); if straw_k and straw_j are connected, then insert k into an array, and set k as tried figure out all the possible untried straws which may intersect with k using above logic and insert them also into the queue insert a seperator into the array to defferenciate between connected component. print the connected component and any two straw from a connected component are touching/intersecting each other directly or indirectly. the complexity is : Time : O(n * log(n)) for sorting + O(n * k * log(n)) where k is degree of connectivity of straws, space : O(n), or more preciously 5N.

Given a string, print out all of the unique characters and the number of times it appeared in the string

public class DuplicateFrequency { public static void main(String[] args) { String str = "I am awesomely in Love With ZoomBA!"; char [] strArray = str.toCharArray(); int [] ar = {1,16,2,3,3,4,4,8,6,5,4}; Map<Character, Integer> map = new TreeMap<Character, Integer>(); for (int i=0; i<strArray.length ; i++) { if (!map.containsKey(strArray[i])) map.put(strArray[i], 1); else map.put(strArray[i],map.get(strArray[i]) +1) ; } map.forEach((k,v) -> System.out.println ("key ="+ k + ", No. of time Repeated "+ v) ); }

Given 2 sorted linked lists, return a linked list that has all the elements and is sorted

public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode head = new ListNode(0); ListNode p=head; ListNode p1=l1; ListNode p2=l2; while(p1!=null && p2!=null){ if(p1.val < p2.val){ p.next = p1; p1 = p1.next; }else{ p.next = p2; p2 = p2.next; } p=p.next; } if(p1!=null){ p.next = p1; } if(p2!=null){ p.next = p2; } return head.next; }

Create a basic minesweeper game that allows for board creation with custom height, width and number of mines. Create a <click> function that will take in a board location and return whether the user has won, lost, or the number of surrounding mines

public abstract class Board { // Board size protected int width, height; // Number of mines on the board protected int numMines; // Number of cells currently marked protected int numMarked; // Number of cells yet to be revealed protected int numUnknown; // Indicates where the mines are hidden protected boolean[][] mines; // The current state of the board protected int[][] board; // Constants for cell contents. The MINE value might be returned by // reveal(), the others are only used internally but will probably be // required in subclasses. public static final int UNKNOWN = -1; public static final int MARKED = -2; public static final int MINE = -3; public Board(int width, int height, int numMines) { this.width = width; this.height = height; this.numMines = numMines; this.numMarked = 0; this.numUnknown = width * height; // Allocate storage for game board and mines mines = new boolean[width][height]; board = new int[width][height]; // Clear the board for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { mines[i][j] = false; board[i][j] = UNKNOWN; } } // Randomly allocate mines. int cells = width * height; int temp = 0; Random rand = new Random(); while (temp < numMines) { int cell = rand.nextInt(); cell = (cell < 0 ? -cell : cell)%cells; if (!mines[cell%width][cell/width]) { mines[cell%width][cell/width] = true; temp++; } } } public void draw() { //Draw representation of Board } public int reveal(int x, int y) { //Reveal the contents of the cell at position (x, y) on the board. } public boolean mark(int x, int y) //Mark' the cell (x, y), probably to indicate that a player thinks there may be a mine there. } public boolean unmark(int x, int y) { //Unmark the previously marked cell at (x, y). } private int closeMines(int x, int y) { //Work out how many neighbours of cell (x, y) contain mines. Return the //number of explosive neighbours. } } public class MineSweeper { // The game board private Board board; // Tokenizer for commands private StreamTokenizer tok; // Various flags used by play() and doCommand() private boolean done, quit, win; // Contents of last cell revealed private int lastCell; public MineSweeper(int width, int height, int mines) { // Create the game board board = new TextBoard(width, height, mines); // Set up the command tokenizer tok = new StreamTokenizer(new InputStreamReader(System.in)); done = win = quit = false; } public void play() throws IOException { //Game play code goes here. On CLick what should happen } public static void main(String[] args) throws IOException { MineSweeper game; if (args.length < 3) { System.out.println("Usage: java MineSweeper width height mines"); System.exit(0); } else { int width = Integer.parseInt(args[0]); int height = Integer.parseInt(args[1]); int mines = Integer.parseInt(args[2]); game = new MineSweeper(width, height, mines); game.play(); } } }

Given a singly linked list of integers, write a function in java that returns true if the given list is palindrome, else returns false

public class ListPalindrome { public boolean isPalindrome(ListNode head) { ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } if (fast != null) { slow = slow.next; } ListNode tail = reverse(slow); ListNode forward = head; ListNode backward = tail; boolean result = true; while (backward != null){ if (forward.payload != backward.payload) { result = false; break; } forward = forward.next; backward = backward.next; } // restore list reverse(tail); return result; } private ListNode reverse(ListNode start) { ListNode tmp, prev = null; ListNode run = start; while (run != null) { tmp = run; run = run.next; tmp.next = prev; prev = tmp; } return prev; } public static void main() { ListNode head = new ListNode(1); ListNode second = new ListNode(2); head.next = second; ListNode third = new ListNode(3); second.next = third; ListNode fourth = new ListNode(2); third.next = fourth; ListNode fifth = new ListNode(1); fourth.next = fifth; System.out.println(new ListPalindrome().isPalindrome(head)); } }

What is the smallest number n by which the given number x must be divided to make it into a perfect square N = find_number(x)

public int smallestSquareNumber(int x) { // y^2 < x < (y+1)^2 // find n and y such that y^2 = (x/n) for (int i = 2; i < x/2; i++) { double newSquare = Math.pow(i, 2); if (newSquare < x) { if (x % newSquare == 0) { return (int) (x / newSquare); } } else if (newSquare == x) { return 1; } } // should never get here. return -1; }

Print the elements of a matrix in a spiral form

vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; int rowStart = 0, rowLength = matrix.size() - 1, columnStart = 0, columnLength = matrix[0].size() - 1; while(rowStart<=rowLength && columnStart<=columnLength) { //Right Sweeping for(int i=columnStart;i<=columnLength;i++) { result.push_back(matrix[rowStart][i]); } //Downward Sweeping for(int i = rowStart + 1; i <= rowLength; i++) { result.push_back(matrix[i][columnLength]); } //Left Sweeping if(rowStart != rowLength) for(int i = columnLength - 1; i >= columnStart; i--) { result.push_back(matrix[rowLength][i]); } //Upward Sweeping if(columnStart != columnLength) for(int i = rowLength - 1; i > rowStart; i--) { result.push_back(matrix[i][columnStart]); } rowStart++;rowLength--; columnStart++;columnLength--; } return result; }


Ensembles d'études connexes

Chapters 1-4 Leadership & Management Pretest

View Set

Chapter 12 Study Guide White Collar Crime

View Set

A.P. Psychology | Structure of a Neuron

View Set

Assessment - Chapter 14 - Skin, Hair, and Nails

View Set