Snippets Collections
//There are many methods provided in the Collections class and we’ll cover a subset of those below:
//binarySearch(): Performs binary search over a List to find the specified object and returns the index if found. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//max(): Finds and returns the maximum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//min(): Finds and returns the minimum element in the Collection. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
//reverse(): Reverses the order of elements in the List passed in as an argument.
//sort(): Sorts the List passed in as an argument. This method is overloaded to also accept a Comparator in order to define a custom sorting algorithm.
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
public class Main {
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<>();
    myList.add(3);
    myList.add(-1);
    myList.add(57);
    myList.add(29);

    Set<String> mySet = new HashSet<>();
    mySet.add("Hello");
    mySet.add("World");

    System.out.println("mySet max: \""+ Collections.max(mySet)+"\"");
    System.out.println();

    System.out.println("myList min: "+ Collections.min(myList));
    System.out.println();

    System.out.println("Index of 57 in myList is: "+Collections.binarySearch(myList, 57));
    System.out.println();


    System.out.println("myList prior to reverse: ");
    printCollection(myList);

    System.out.println();

    Collections.reverse(myList);
    System.out.println("myList reversed: ");
    printCollection(myList);

    System.out.println();

    System.out.println("myList prior to sort: ");
    printCollection(myList);

    System.out.println();

    Collections.sort(myList);
    System.out.println("myList after sort: ");
    printCollection(myList);


  }

  public static void printCollection(Collection<?> collection){
    Iterator<?> myItr = collection.iterator();

    while(myItr.hasNext()){
      System.out.println(myItr.next());
    }
  }
}
import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
tortoise = top
hare = top

forever:
     if hare == end :
         return 'No Loop Found'
     hare = hare.next
 
     if hare == end :
         return 'No Loop Found'
     hare = hare.next
 
     tortoise = tortoise.next
 
     if hare == tortoise:
         return 'Loop Found'
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;

class Pair {
    int x, y;

    public Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class FloodFill
{
    // Below arrays details all 8 possible movements
    private static final int[] row = { -1, -1, -1, 0, 0, 1, 1, 1 };
    private static final int[] col = { -1, 0, 1, -1, 1, -1, 0, 1 };

    // check if it is possible to go to pixel (x, y) from
    // current pixel. The function returns false if the pixel
    // has different color or it is not a valid pixel
    public static boolean isSafe(char[][] M, int m, int n,
                                int x, int y, char target)
    {
        return x >= 0 && x < m && y >= 0 && y < n
                && M[x][y] == target;
    }

    // Flood fill using BFS
    public static void floodfill(char[][] M, int x, int y, char replacement)
    {
        int m = M.length;
        int n = M[0].length;

        // create a queue and enqueue starting pixel
        Queue<Pair> q = new ArrayDeque<>();
        q.add(new Pair(x, y));

        // get target color
        char target = M[x][y];

        // run till queue is not empty
        while (!q.isEmpty())
        {
            // pop front node from queue and process it
            Pair node = q.poll();

            // (x, y) represents current pixel
            x = node.x;
            y = node.y;

            // replace current pixel color with that of replacement
            M[x][y] = replacement;

            // process all 8 adjacent pixels of current pixel and
            // enqueue each valid pixel
            for (int k = 0; k < row.length; k++)
            {
                // if adjacent pixel at position (x + row[k], y + col[k]) is
                // a valid pixel and have same color as that of current pixel
                if (isSafe(M, m, n, x + row[k], y + col[k], target))
                {
                    // enqueue adjacent pixel
                    q.add(new Pair(x + row[k], y + col[k]));
                }
            }
        }
    }

    public static void main(String[] args)
    {
        // matrix showing portion of the screen having different colors
        char[][] M = {
            "YYYGGGGGGG".toCharArray(),
            "YYYYYYGXXX".toCharArray(),
            "GGGGGGGXXX".toCharArray(),
            "WWWWWGGGGX".toCharArray(),
            "WRRRRRGXXX".toCharArray(),
            "WWWRRGGXXX".toCharArray(),
            "WBWRRRRRRX".toCharArray(),
            "WBBBBRRXXX".toCharArray(),
            "WBBXBBBBXX".toCharArray(),
            "WBBXXXXXXX".toCharArray()
        };

        // start node
        int x = 3, y = 9;   // target color = "X"

        // replacement color
        char replacement = 'C';

        // replace target color with replacement color
        floodfill(M, x, y, replacement);

        // print the colors after replacement
        for (int i = 0; i < M.length; i++) {
            System.out.println(Arrays.toString(M[i]));
        }
    }
}
int maxSubArraySum(int a[], int size) 
{ 
int max_so_far = 0, max_ending_here = 0; 
for (int i = 0; i < size; i++) 
{ 
	max_ending_here = max_ending_here + a[i]; 
	if (max_ending_here < 0) 
		max_ending_here = 0; 

	/* Do not compare for all elements. Compare only 
		when max_ending_here > 0 */
	else if (max_so_far < max_ending_here) 
		max_so_far = max_ending_here; 
} 
return max_so_far; 
} 
star

Sun Dec 25 2022 21:59:38 GMT+0000 (Coordinated Universal Time)

#java #generics #algorithms
star

Thu Jan 02 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://en.wikipedia.org/wiki/PageRank

#javascript #python #search #historicalcode #google #algorithms
star

Thu Dec 26 2019 19:01:13 GMT+0000 (Coordinated Universal Time) https://www.techiedelight.com/flood-fill-algorithm/

#java #logic #algorithms #interesting #arrays
star

Wed Dec 25 2019 10:57:06 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/

#c++ #algorithms #interviewquestions #arrays

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension