Showing posts with label Programs. Show all posts
Showing posts with label Programs. Show all posts
Monotone Increasing Digits
Given a non-negative integer N, find the largest number that is less
than or equal to N with monotone increasing digits.
(An integer has monotone increasing digits if and only if each pair
of adjacent digits x and y satisfy x <= y.)
Examples :
Input: N = 10
Output: 9
Input: N = 1234
Output: 1234
Input: N = 332
Output: 299
import java.util.*;
class Solution {
public static int monotoneIncreasingDigits(int N) {
String S = String.valueOf(N);
String ans = "";
search: for (int i = 0; i < S.length(); ++i) {
for (char d = '1'; d <= '9'; ++d) {
if (S.compareTo(ans + repeat(d, S.length() - i)) < 0) {
ans += (char) (d - 1);
continue search;
}
}
ans += '9';
}
return Integer.parseInt(ans);
}
public static String repeat(char c, int count) {
StringBuilder sb = new StringBuilder(count);
for (int i = 0; i < count; ++i) sb.append(c);
return sb.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = Integer.parseInt(sc.nextLine());
int output = monotoneIncreasingDigits(num);
System.out.print(output);
}
}
Sort based on frequency of characters
Given a string, sort it in decreasing order based on the frequency
of characters.
Input: "tree"
Output:"eert"
Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr"
is also a valid answer.
import java.util.*;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String output=frequencySort(input);
System.out.println(output);
}
public static String frequencySort(String s) {
int[][] count = new int[256][2];
for(char c: s.toCharArray()) {
count[c][0] = c;
count[c][1]++;
}
Arrays.sort(count, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[1] == b[1] ? 0 : (a[1] < b[1] ? 1 : -1);
}
});
StringBuilder sb = new StringBuilder();
for(int i=0; i<256; i++) {
if (count[i][1] > 0) {
for(int j=0; j<count[i][1]; j++) {
sb.append((char)count[i][0]);
}
}
}
return sb.toString();
}
}
Missing Positive Integer
Find the
smallest positive number missing from an unsorted array .
Examples
Input: {2, 3, 7, 6, 8, -1, -10, 15}
Output: 1
Input: { 2, 3, -7, 6, 8, 1, -10, 15 }
Output: 4
Input: {1, 1, 0, -1, -2}
Output: 2
// java program to find maximum
// element
import java.util.*;
class Solution
{
/* Utility function that puts all non-positive
(0 and negative) numbers on left side of
arr[] and return count of such numbers */
static int segregate (int arr[], int size)
{
int j = 0, i;
for(i = 0; i < size; i++)
{
if (arr[i] <= 0)
{
int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
// increment count of non-positive
// integers
j++;
}
}
return j;
}
/* Find the smallest positive missing
number in an array that contains
all positive integers */
static int findMissingPositive(int arr[], int size)
{
int i;
// Mark arr[i] as visited by making
// arr[arr[i] - 1] negative. Note that
// 1 is subtracted because index start
// from 0 and positive numbers start from 1
for(i = 0; i < size; i++)
{
if(Math.abs(arr[i]) - 1 < size && arr[Math.abs(arr[i]) - 1] > 0)
arr[Math.abs(arr[i]) - 1] = -arr[Math.abs(arr[i]) - 1];
}
// Return the first index value at which
// is positive
for(i = 0; i < size; i++)
if (arr[i] > 0)
return i+1; // 1 is added becuase indexes
// start from 0
return size+1;
}
/* Find the smallest positive missing
number in an array that contains
both positive and negative integers */
static int findMissing(int arr[], int size)
{
// First separate positive and
// negative numbers
int shift = segregate (arr, size);
int arr2[] = new int[size-shift];
int j=0;
for(int i=shift;i<size;i++)
{
arr2[j] = arr[i];
j++;
}
// Shift the array and call
// findMissingPositive for
// positive part
return findMissingPositive(arr2, j);
}
// main function
public static void main (String[] args)
{
Scanner sc= new Scanner(System.in);
int numInputs = Integer.parseInt(sc.nextLine());
if(numInputs>0){
int arra[] = new int[numInputs];
for (int i=0;i<numInputs ;i++ ) {
arra[i]= Integer.parseInt(sc.nextLine());
}
// int arr[] = {0, 10, 2, -10, -20};
// int arr_size = arr.length;
//int missing = findMissing(arr, arr_size);
int missing = findMissing(arra,numInputs);
System.out.println(missing);
}
}
}
Count Digits that doesn't contain 3
-
Given a number n, write a function that returns count of numbers from 1 to n that don’t contain digit 3 in their decimal representation.
Examples:
Input: n
= 10
Output: 9
Input: n
= 45
Output: 31
Numbers 3, 13, 23, 30, 31, 32,
33, 34, 35, 36, 37, 38, 39, 43 contain digit 3.
// Java program to count numbers that not contain 3
import java.io.*;
import java.util.*;
class Solution
{
// Function that returns count of numbers which
// are in range from 1 to n
// and not contain 3 as a digit
static int count(int n)
{
// Base cases (Assuming n is not negative)
if (n < 3)
return n;
if (n >= 3 && n < 10)
return n-1;
// Calculate 10^(d-1) (10 raise to the power d-1) where d is
// number of digits in n. po will be 100 for n = 578
int po = 1;
while (n/po > 9)
po = po*10;
// find the most significant digit (msd is 5 for 578)
int msd = n/po;
if (msd != 3)
// For 578, total will be 4*count(10^2 - 1) + 4 + count(78)
return count(msd)*count(po - 1) + count(msd) + count(n%po);
else
// For 35, total will be equal to count(29)
return count(msd*po - 1);
}
// Driver program
public static void main (String[] args)
{
int n = 578;
Scanner sc = new Scanner(System.in);
int m = Integer.parseInt(sc.nextLine());
if(m>=0){
System.out.println(count(m));
}
}
}
Validating ISBN
Validating ISBN: Write a C program to define a structure Book with the attributes, book title,
author, subject, isbn number, Based on the given input values display the books information if the
given ISBN is valid.
Following are the rules to verify whether the given ISBN is a valid or not.
The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10
check digit – which is the last digit of the ten-digit ISBN – must range from 0 to 10 (the symbol X is
used for 10), and must be such that the sum of all the ten digits, each multiplied by its (integer)
weight, descending from 10 to 1, is a multiple of 11.
author, subject, isbn number, Based on the given input values display the books information if the
given ISBN is valid.
Following are the rules to verify whether the given ISBN is a valid or not.
The 2001 edition of the official manual of the International ISBN Agency says that the ISBN-10
check digit – which is the last digit of the ten-digit ISBN – must range from 0 to 10 (the symbol X is
used for 10), and must be such that the sum of all the ten digits, each multiplied by its (integer)
weight, descending from 10 to 1, is a multiple of 11.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
_Bool isValidISBN(long);
int getLength(char*);
int main(int argc, char *argv[]) {
struct Book {
char *bookTitle;
char *bookAuthor;
char *subject;
long isbn;
};
struct Book book[5];
int n;
char *s = (char *)malloc(sizeof(char)*100);
int length = getLength(s);
scanf("%d", &n);
for(int i=0; i<n; i++) {
scanf("%s", s);
fflush(stdin);
int length = getLength(s);
book[i].bookTitle = (char *)malloc(sizeof(char) * length);
strcpy(book[i].bookTitle, s);
scanf("%s", s);
fflush(stdin);
length = getLength(s);
book[i].bookAuthor = (char *)malloc(sizeof(char) * length);
strcpy(book[i].bookAuthor, s);
scanf("%s", s);
length = getLength(s);
fflush(stdin);
book[i].subject = (char *)malloc(sizeof(char) * length);
strcpy(book[i].subject, s);
scanf("%ld", &book[i].isbn);
if(isValidISBN(book[i].isbn)==true) {
printf("{Book Title : %s; ", book[i].bookTitle);
printf("Book Author : %s; ", book[i].bookAuthor);
printf("Subject : %s; ", book[i].subject);
printf("ISBN : %ld}\n", book[i].isbn);
}
}
}
int getLength(char *s) {
int length = 0;
while(s[length]!='\0') {
length++;
}
return length;
}
_Bool isValidISBN(long isbn) {
long sum = 0;
int i = 1;
while(isbn>0) {
sum = sum + (isbn)%10 * i;
isbn = isbn / 10;
i++;
}
if(sum%11==0)
return true;
return false;
}
Project Euler #7: 10001st prime
By listing the first six prime numbers: and , we can see that the prime is .
What is the prime number?
What is the prime number?
a = [0]*200008
for i in range(2,200000):
if (a[i] == 1):
continue
for j in range(2*i,200000,i):
a[j] = 1
primes = []
for i in range(2,200000):
if a[i] == 0:
primes.append(i)
p = int(input())
for _ in range(p):
t = int(input())
print(primes[t-1])
Sum of Factorials of the digits of N.
Sum of Factorial of the digits of the given number: Write a python program to compute sum of
the factorials of each digit of a given integer. Write a separate function for calculating the
factorial of a number.
the factorials of each digit of a given integer. Write a separate function for calculating the
factorial of a number.
def fact(n):
result = 1
for i in range(n):
result *= i + 1
return result
def sum_of_fact(n):
result = 0
if(n <= 0):
return 1
else:
while n > 0:
result += fact(n % 10)
n = n // 10
return result
print(sum_of_fact(int(input())))
import java.util.Scanner; public class Solution { public static long factorialN(long n) { if (n <= 0) return 1; else return n * factorialN(n-1); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); long n = scan.nextLong(); int sum = 0; if(n <= 0) { System.out.println("1"); } else { while(n != 0) { sum = sum + (int)factorialN(n%10); n = n/10; } System.out.println(sum); } } }C#include <stdio.h> long long int factorialN(long long int n) { if (n <= 0) return 1; else return n * factorialN(n-1); } int main(int argc, char const *argv[]) { long long int n = 0; long long int sum = 0; scanf("%llu",&n); if(n <= 0) { printf("1"); } else { while(n != 0) { sum = sum + factorialN(n%10); n = n/10; } printf("%llu\n",sum); } return 0; }
Moving all Zeros to the Left Side of the Array
Moving all Zeros to the Left Side of the Array: Write a program to move all the zeros on the
left side of the array while maintaining the relative order of non-zero elements. You should not
use another array.
Solution :
C
left side of the array while maintaining the relative order of non-zero elements. You should not
use another array.
Solution :
C
/*
Float all zeros to the left of an array
*/
#include <stdio.h>
#include <stdlib.h>
void float_zeros(int *arr, int len);
void print_array(int *arr, int len);
int main(void) {
int n = 0, *arr = NULL, i = 0;
scanf("%d", &n);
if(n <= 0) {
fprintf(stderr, "The array size can't be zero or negative\n");
return 1;
}
arr = (int*)calloc(1, n * sizeof(int));
for(i = 0; i < n; i++)
scanf("%d", &arr[i]);
float_zeros(arr, n);
print_array(arr, n);
free(arr);
return 0;
}
void float_zeros(int *arr, int len) {
/*
Find all the 0s in arr, and float them to the left end of arr.
*/
int i = 0, prev = 0, j = 0, k = 0, temp = 0;
while(i < len) {
// Find zeros
if(*(arr + i) == 0) {
// Found a zero. Now float it.
// To do that, we need where to float it to.
// That would be prev.
for(j = i; j > prev; j--) {
k = j - 1;
temp = *(arr + j);
*(arr + j) = *(arr + k);
*(arr + k) = temp;
}
prev++;
}
i++;
}
}
void print_array(int *arr, int len) {
/*
Prints an int array of length len
*/
int i = 0;
while(i < len) {
printf("%d", *(arr + i));
if(i != len - 1)
printf(" ");
i++;
}
printf("\n");
}
JAVA:
/*
Float zeros
*/
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int n = 0;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
if(n <= 0)
System.err.println("The array size can't be zero or negative");
int arr[] = new int[n];
for(int i = 0; i < n; i++)
arr[i] = sc.nextInt();
sc.close();
// Changing the array elements here.
int i = 0, prev = 0;
while(i < n) {
// Find a zero
if(arr[i] == 0) {
// Found zero.
// Float it
for(int j = i; j > prev; j--) {
int k = j - 1, temp = arr[k];
arr[k] = arr[j];
arr[j] = temp;
}
prev++;
}
i++;
}
for(i = 0; i < n; i++) {
System.out.print(arr[i]);
if(i != n - 1)
System.out.print(" ");
}
System.out.println("");
}
}
Count divisors of product of array elements
Given an array with N elements, the task is to find the count of factors of a number X which is product of all array elements.
Example:
Input : 2 4 6
Output : 10 2 * 4 * 6 = 48,the factors of 48 are 1, 2,
3, 4, 6, 8, 12, 16, 24, 48 whose count is 10.
Solution:
JAVA
import java.util.*;
import java.lang.*;
import java.io.*;
class Solution {
static List<Integer> ll = new ArrayList<>();
static final int MAX = 101;
static boolean[] isP = new boolean[MAX];
static Scanner sc = new Scanner(System.in);
public static void main (String[] args) {
//code
init();
int n = sc.nextInt();
while(n-- > 0) solve();
}
public static void solve(){
int n = sc.nextInt();
if(n>0){
int[] arr = new int[n];
long ans = 1;
int flag =0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
if(arr[i]>=1){
flag=1;
countFact(arr[i], map);
}
}
for(int key : map.keySet()){
ans *= (map.get(key) + 1);
}
if(flag==1){
System.out.println(ans);}
}
}
static void countFact(int n, Map<Integer, Integer> map){
int i = 0;
while(n != 1){
while(n % ll.get(i) == 0){
n = n / ll.get(i);
map.put(ll.get(i),
map.getOrDefault(ll.get(i), 0) + 1);
}
i++;
}
}
static void init(){
Arrays.fill(isP, true);
isP[0] = isP[1] = false;
for(int i = 2; i * i < MAX; i++){
if(isP[i]){
for(int j = i * i; j < MAX; j += i){
isP[j] = false;
}
}
}
for(int i = 2; i < MAX; i++){
if(isP[i]) ll.add(i);
}
}
}
Example:
Input : 2 4 6
Output : 10 2 * 4 * 6 = 48,the factors of 48 are 1, 2,
3, 4, 6, 8, 12, 16, 24, 48 whose count is 10.
Solution:
JAVA
import java.util.*;
import java.lang.*;
import java.io.*;
class Solution {
static List<Integer> ll = new ArrayList<>();
static final int MAX = 101;
static boolean[] isP = new boolean[MAX];
static Scanner sc = new Scanner(System.in);
public static void main (String[] args) {
//code
init();
int n = sc.nextInt();
while(n-- > 0) solve();
}
public static void solve(){
int n = sc.nextInt();
if(n>0){
int[] arr = new int[n];
long ans = 1;
int flag =0;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
arr[i] = sc.nextInt();
if(arr[i]>=1){
flag=1;
countFact(arr[i], map);
}
}
for(int key : map.keySet()){
ans *= (map.get(key) + 1);
}
if(flag==1){
System.out.println(ans);}
}
}
static void countFact(int n, Map<Integer, Integer> map){
int i = 0;
while(n != 1){
while(n % ll.get(i) == 0){
n = n / ll.get(i);
map.put(ll.get(i),
map.getOrDefault(ll.get(i), 0) + 1);
}
i++;
}
}
static void init(){
Arrays.fill(isP, true);
isP[0] = isP[1] = false;
for(int i = 2; i * i < MAX; i++){
if(isP[i]){
for(int j = i * i; j < MAX; j += i){
isP[j] = false;
}
}
}
for(int i = 2; i < MAX; i++){
if(isP[i]) ll.add(i);
}
}
}
Reorganize The Array
Reorganize The Array :
Given an array of elements of length N , ranging from 0 to N-1 , your task is to write a program that rearranges the elements of the array. All elements may not be present in the array, if element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place.
Examples:
Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : {-1, 1, 2, 3, 4, -1, 6, -1, -1, 9}
Solution :
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int T,i,n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
int *arr,k;
arr = (int *)calloc(n+1,sizeof(int));
for(i = 0; i < n; i++) {
scanf("%d", &k);
if(k >= 0) {
arr[k]++;
}
}
for(i = 0; i < n; i++) {
if(arr[i] > 0) {
printf("%d ", i);
}
else {
printf("-1 ");
}
}
printf("\n");
}
return 0;
}
Given an array of elements of length N , ranging from 0 to N-1 , your task is to write a program that rearranges the elements of the array. All elements may not be present in the array, if element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place.
Examples:
Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : {-1, 1, 2, 3, 4, -1, 6, -1, -1, 9}
Solution :
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int T,i,n;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
int *arr,k;
arr = (int *)calloc(n+1,sizeof(int));
for(i = 0; i < n; i++) {
scanf("%d", &k);
if(k >= 0) {
arr[k]++;
}
}
for(i = 0; i < n; i++) {
if(arr[i] > 0) {
printf("%d ", i);
}
else {
printf("-1 ");
}
}
printf("\n");
}
return 0;
}
Pascal's Triangle
Pascal's Triangle :
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients.'
eg:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Algorithm for Pascal Triangle:
In mathematics, Pascal's triangle is a triangular array of the binomial coefficients.'
eg:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Algorithm for Pascal Triangle:
Hotel Program using OOPs Concepts in Java
/*
the Hotel is an ArrayList of Reservations
it allows a person to request a room and cancel their reservation
also we can add more rooms
*/
import java.util.ArrayList;
public class Hotel{
//instance variable, ArrayList tracks current reservations
private ArrayList<Reservation> rooms;
//constructors, can specify how many rooms to start with
//default is 5 rooms
public Hotel(){
rooms = new ArrayList<Reservation>();
rooms.ensureCapacity(5);
for (int i = 0; i < 5; i++)
rooms.add(null);
}
public Hotel(int numRooms){
rooms = new ArrayList();
rooms.ensureCapacity(numRooms);
for(int i = 0; i< numRooms; i++)
rooms.add(null);
}
//adds more rooms to the hotel, returns true on success
public boolean buildRooms(int num){
//make sure the parameter is valid
if(num<=0)return false;
//increase the capacity of the Vector
rooms.ensureCapacity(rooms.size() + num);
for(int i = 0; i < num; i++)
rooms.add(null);
//report succes
return true;
}
//reserves and returns an available room
//or returns -1 if the hotel is full
public int reserveRoom(String person) {
boolean emptyRoom = false;
int i = 0;
for ( i = 0; i < rooms.size(); i++) {
if (rooms.get(i) == null) {
emptyRoom = true;
break;
}
}
if (emptyRoom == true) {
Reservation customer = new Reservation(person,i);
//rooms.get(i) = customer;
rooms.set(i, customer);
return i;
}
return -1;
}
//reserves a particular room for this person
//returns false on failure (eg. room is already reserved)
public boolean reserveRoom(String person, int roomNum) {
if(rooms.get(roomNum) == null){
Reservation customer = new Reservation(person,roomNum);
rooms.set(roomNum, customer);
return true;
}
else {
return false;
}
}
//cancels all reservations by this person
public void cancelReservations(String person) {
for (int i = 0; i < rooms.size(); i++){
if (rooms.get(i)!=null){
if (rooms.get(i).getName().compareTo(person)==0) {
rooms.set(i, null);
}
}
}
}
//prints out all the current reservations to the screen
//also should display the total number of reservations and vacancies
public void printReservations() {
for (int i = 0; i< rooms.size(); i++ ) {
if (rooms.get(i)!=null){
System.out.println(rooms.get(i).getName() +"-room number->"+ rooms.get(i).getRoom());
}
}
}
}
........***
/*
Reservation class, stores the person and room number in the Hotel
*/
public class Reservation{
//instance variables
private String name;
private int roomNumber;
//constructors, must supply the name, and optionally a room
public Reservation(String person){
this.name = person;
}
public Reservation(String person, int room){
this.name = person;
this.roomNumber = room;
}
//mutators, set the room number or name
public void setRoom(int newroom){
roomNumber = newroom;
}
public void setName(String newname){
name = newname;
}
//accessors, return the room number or name
public int getRoom(){
return roomNumber;
}
public String getName(){
return name;
}
}
the Hotel is an ArrayList of Reservations
it allows a person to request a room and cancel their reservation
also we can add more rooms
*/
import java.util.ArrayList;
public class Hotel{
//instance variable, ArrayList tracks current reservations
private ArrayList<Reservation> rooms;
//constructors, can specify how many rooms to start with
//default is 5 rooms
public Hotel(){
rooms = new ArrayList<Reservation>();
rooms.ensureCapacity(5);
for (int i = 0; i < 5; i++)
rooms.add(null);
}
public Hotel(int numRooms){
rooms = new ArrayList();
rooms.ensureCapacity(numRooms);
for(int i = 0; i< numRooms; i++)
rooms.add(null);
}
//adds more rooms to the hotel, returns true on success
public boolean buildRooms(int num){
//make sure the parameter is valid
if(num<=0)return false;
//increase the capacity of the Vector
rooms.ensureCapacity(rooms.size() + num);
for(int i = 0; i < num; i++)
rooms.add(null);
//report succes
return true;
}
//reserves and returns an available room
//or returns -1 if the hotel is full
public int reserveRoom(String person) {
boolean emptyRoom = false;
int i = 0;
for ( i = 0; i < rooms.size(); i++) {
if (rooms.get(i) == null) {
emptyRoom = true;
break;
}
}
if (emptyRoom == true) {
Reservation customer = new Reservation(person,i);
//rooms.get(i) = customer;
rooms.set(i, customer);
return i;
}
return -1;
}
//reserves a particular room for this person
//returns false on failure (eg. room is already reserved)
public boolean reserveRoom(String person, int roomNum) {
if(rooms.get(roomNum) == null){
Reservation customer = new Reservation(person,roomNum);
rooms.set(roomNum, customer);
return true;
}
else {
return false;
}
}
//cancels all reservations by this person
public void cancelReservations(String person) {
for (int i = 0; i < rooms.size(); i++){
if (rooms.get(i)!=null){
if (rooms.get(i).getName().compareTo(person)==0) {
rooms.set(i, null);
}
}
}
}
//prints out all the current reservations to the screen
//also should display the total number of reservations and vacancies
public void printReservations() {
for (int i = 0; i< rooms.size(); i++ ) {
if (rooms.get(i)!=null){
System.out.println(rooms.get(i).getName() +"-room number->"+ rooms.get(i).getRoom());
}
}
}
}
........***
/*
Reservation class, stores the person and room number in the Hotel
*/
public class Reservation{
//instance variables
private String name;
private int roomNumber;
//constructors, must supply the name, and optionally a room
public Reservation(String person){
this.name = person;
}
public Reservation(String person, int room){
this.name = person;
this.roomNumber = room;
}
//mutators, set the room number or name
public void setRoom(int newroom){
roomNumber = newroom;
}
public void setName(String newname){
name = newname;
}
//accessors, return the room number or name
public int getRoom(){
return roomNumber;
}
public String getName(){
return name;
}
}
Maximum Neighbor count
Write a program to display the Count of the Island that has Maximum number of Neighbors.
input:
{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
Output : 8;
// Java program to count islands in boolean 2D matrix
import java.util.*;
import java.lang.*;
import java.io.*;
class Islands
{
//No of rows and columns
static final int ROW = 5, COL = 5;
// A function to check if a given cell (row, col) can
// be included in DFS
boolean isSafe(int M[][], int row, int col,
boolean visited[][])
{
// row number is in range, column number is in range
// and value is 1 and not yet visited
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
(M[row][col]==1 && !visited[row][col]);
}
// A utility function to do DFS for a 2D boolean matrix.
// It only considers the 8 neighbors as adjacent vertices
static int GlobCount=0;
void DFS(int M[][], int row, int col, boolean visited[][])
{
// These arrays are used to get row and column numbers
// of 8 neighbors of a given cell
int rowNbr[] = new int[] {-1, -1, -1, 0, 0, 1, 1, 1};
int colNbr[] = new int[] {-1, 0, 1, -1, 1, -1, 0, 1};
// Mark this cell as visited
visited[row][col] = true;
// Recur for all connected neighbours
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited) ){
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
GlobCount++;
}
}
// The main function that returns count of islands in a given
// boolean 2D matrix
int countIslands(int M[][])
{
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
boolean visited[][] = new boolean[ROW][COL];
int max=0;
// Initialize count as 0 and travese through the all cells
// of given matrix
int count = 0;
for (int i = 0; i < ROW; ++i){
for (int j = 0; j < COL; ++j){
if (M[i][j]==1 && !visited[i][j]) // If a cell with
{ // value 1 is not
// visited yet, then new island found, Visit all
// cells in this island and increment island count
DFS(M, i, j, visited);
++count;
}
if(GlobCount>max){
max=GlobCount;
GlobCount=0;
}
}}
return count;
}
// Driver method
public static void main (String[] args) throws java.lang.Exception
{
int M[][]= new int[][] {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
};
Islands I = new Islands();
System.out.println("Number of islands is: "+ I.countIslands(M));
}
} //Contributed by Aakash Hasija
input:
{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 1, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
Output : 8;
// Java program to count islands in boolean 2D matrix
import java.util.*;
import java.lang.*;
import java.io.*;
class Islands
{
//No of rows and columns
static final int ROW = 5, COL = 5;
// A function to check if a given cell (row, col) can
// be included in DFS
boolean isSafe(int M[][], int row, int col,
boolean visited[][])
{
// row number is in range, column number is in range
// and value is 1 and not yet visited
return (row >= 0) && (row < ROW) &&
(col >= 0) && (col < COL) &&
(M[row][col]==1 && !visited[row][col]);
}
// A utility function to do DFS for a 2D boolean matrix.
// It only considers the 8 neighbors as adjacent vertices
static int GlobCount=0;
void DFS(int M[][], int row, int col, boolean visited[][])
{
// These arrays are used to get row and column numbers
// of 8 neighbors of a given cell
int rowNbr[] = new int[] {-1, -1, -1, 0, 0, 1, 1, 1};
int colNbr[] = new int[] {-1, 0, 1, -1, 1, -1, 0, 1};
// Mark this cell as visited
visited[row][col] = true;
// Recur for all connected neighbours
for (int k = 0; k < 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited) ){
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
GlobCount++;
}
}
// The main function that returns count of islands in a given
// boolean 2D matrix
int countIslands(int M[][])
{
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
boolean visited[][] = new boolean[ROW][COL];
int max=0;
// Initialize count as 0 and travese through the all cells
// of given matrix
int count = 0;
for (int i = 0; i < ROW; ++i){
for (int j = 0; j < COL; ++j){
if (M[i][j]==1 && !visited[i][j]) // If a cell with
{ // value 1 is not
// visited yet, then new island found, Visit all
// cells in this island and increment island count
DFS(M, i, j, visited);
++count;
}
if(GlobCount>max){
max=GlobCount;
GlobCount=0;
}
}}
return count;
}
// Driver method
public static void main (String[] args) throws java.lang.Exception
{
int M[][]= new int[][] {{1, 1, 0, 0, 0},
{0, 1, 0, 0, 1},
{1, 0, 0, 1, 1},
{0, 0, 0, 0, 0},
{1, 0, 1, 0, 1}
};
Islands I = new Islands();
System.out.println("Number of islands is: "+ I.countIslands(M));
}
} //Contributed by Aakash Hasija
k th largest element using Min Heap
Implement a priority queue to find the k th largest element using min heap.
----------------------------------Program------------------------------
import java.util.*;
public class PriorityQueue {
int[] arr ;
int size;
int max;
public PriorityQueue()
{
size = 0;
max = 20;
arr = new int[max];
}
public void insert(int e)//E e)
{
if(size==max)
{
System.out.println("full");
}
else
{
arr[size++] = e;
heapify(); //
}
}
public void heapify() //heapfiy from down to up
{
int i = size-1;
int parent = (i-1)/2;
while(arr[parent]> arr[i]) //heap min heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void heapify(int index) //heapfiy from down to up //HEAPIFY UP
{
int i = index;
int parent = (i-1)/2;
while(arr[parent]> arr[i]) //heap min heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void delete_min()
{
int min=0;
if(size!=0)
{
min = arr[0];
arr[0] = arr[size-1]; //copy last emelent to front
if(!(size<=3))
arr[size-1] =0;
else
arr[size-1] =99999;
size--; //ignore last element
}
heapifyDown(); // incomplete code
}
public void heapifyDown() //heapify min heap from root node..after deleteion of root node new lel,ement is root node
{
for(int parent = 0 ; parent< ((size)/2 ) ;parent++) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]< arr[parent] && (arr[left] <=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left-1; // -1 to compensate parent++ in for loop
}
else if(arr[right]< arr[parent] && (arr[left] >= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right-1; // -1 to compensate parent++ in for loop
}
else
break;
}
}
public void heapifyDown(int index) //heapfiy min heap from a particular index
{
int tempParent = getParent(index);
for(int parent = tempParent ; parent< (size)/2 ;) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]< arr[parent] && (arr[left] <=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left;
}
else if(arr[right]< arr[parent] && (arr[left] >= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right;
}
else
break;
}
}
private int getParent(int index) //get parent index for a child
{
return (index-1)/2;
}
private int right(int index)
{
return (index*2) + 2;
}
private int left(int index)
{
return (index*2) + 1;
}
public boolean isChild(int index)
{
if(index >= ( size/2) +1 )
return true;
else
return false;
}
public void swap(int index1, int index2)
{
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public int extract_min()
{
int min = 0;
if(size!=0)
{
min = arr[0];
}
return min;
}
public void list()
{
for(int i =0 ;i<size;i++)
{
System.out.print(arr[i]);
if(i!=size-1)
{
System.out.print(" ");
}
}
System.out.println("");
}
public void modify(int index, int value)
{
for(int i =0 ;i<size;i++)
{
if(i+1==index)
{
int temp = arr[i];
arr[i]=value;
if(value>temp)
heapifyDown(i);
else if(value<temp)
heapify(i); //smaller value there for heapify up
break;
}
}
}
public int getLargest(int m) throws Exception
{
if(m<=size){
int tsize = size;
int u=0;
int[] q= new int[100];
while(u!=tsize-m)
{
q[u]= extract_min();
u++;
delete_min();
}
int p= extract_min();
for(int k=0;k<u;k++)
insert(q[k]);
return p;
}
else
{
throw new Exception("No largest element found");
}
}
public static void main(String[] args) throws Exception {
PriorityQueue pq = new PriorityQueue();
pq.insert(1);
pq.insert(2);
pq.insert(3);
pq.insert(4);
pq.insert(5);
int s=pq.getLargest(1);
System.out.println(s);
}
}
----------------------------------Program------------------------------
import java.util.*;
public class PriorityQueue {
int[] arr ;
int size;
int max;
public PriorityQueue()
{
size = 0;
max = 20;
arr = new int[max];
}
public void insert(int e)//E e)
{
if(size==max)
{
System.out.println("full");
}
else
{
arr[size++] = e;
heapify(); //
}
}
public void heapify() //heapfiy from down to up
{
int i = size-1;
int parent = (i-1)/2;
while(arr[parent]> arr[i]) //heap min heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void heapify(int index) //heapfiy from down to up //HEAPIFY UP
{
int i = index;
int parent = (i-1)/2;
while(arr[parent]> arr[i]) //heap min heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void delete_min()
{
int min=0;
if(size!=0)
{
min = arr[0];
arr[0] = arr[size-1]; //copy last emelent to front
if(!(size<=3))
arr[size-1] =0;
else
arr[size-1] =99999;
size--; //ignore last element
}
heapifyDown(); // incomplete code
}
public void heapifyDown() //heapify min heap from root node..after deleteion of root node new lel,ement is root node
{
for(int parent = 0 ; parent< ((size)/2 ) ;parent++) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]< arr[parent] && (arr[left] <=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left-1; // -1 to compensate parent++ in for loop
}
else if(arr[right]< arr[parent] && (arr[left] >= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right-1; // -1 to compensate parent++ in for loop
}
else
break;
}
}
public void heapifyDown(int index) //heapfiy min heap from a particular index
{
int tempParent = getParent(index);
for(int parent = tempParent ; parent< (size)/2 ;) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]< arr[parent] && (arr[left] <=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left;
}
else if(arr[right]< arr[parent] && (arr[left] >= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right;
}
else
break;
}
}
private int getParent(int index) //get parent index for a child
{
return (index-1)/2;
}
private int right(int index)
{
return (index*2) + 2;
}
private int left(int index)
{
return (index*2) + 1;
}
public boolean isChild(int index)
{
if(index >= ( size/2) +1 )
return true;
else
return false;
}
public void swap(int index1, int index2)
{
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public int extract_min()
{
int min = 0;
if(size!=0)
{
min = arr[0];
}
return min;
}
public void list()
{
for(int i =0 ;i<size;i++)
{
System.out.print(arr[i]);
if(i!=size-1)
{
System.out.print(" ");
}
}
System.out.println("");
}
public void modify(int index, int value)
{
for(int i =0 ;i<size;i++)
{
if(i+1==index)
{
int temp = arr[i];
arr[i]=value;
if(value>temp)
heapifyDown(i);
else if(value<temp)
heapify(i); //smaller value there for heapify up
break;
}
}
}
public int getLargest(int m) throws Exception
{
if(m<=size){
int tsize = size;
int u=0;
int[] q= new int[100];
while(u!=tsize-m)
{
q[u]= extract_min();
u++;
delete_min();
}
int p= extract_min();
for(int k=0;k<u;k++)
insert(q[k]);
return p;
}
else
{
throw new Exception("No largest element found");
}
}
public static void main(String[] args) throws Exception {
PriorityQueue pq = new PriorityQueue();
pq.insert(1);
pq.insert(2);
pq.insert(3);
pq.insert(4);
pq.insert(5);
int s=pq.getLargest(1);
System.out.println(s);
}
}
Kth Smallest Element using Max Heap
Implement a priority queue to find the k th smallest element using max heap.
------------------------------------Program----------------------------------------------------------------
import java.util.*;
class NoSmallestElementFound extends Exception
{
NoSmallestElementFound(String s)
{
super(s);
}
}
public class PriorityQueue {
int[] arr ;
int size;
int max;
public PriorityQueue()
{
size = 0;
max = 20;
arr = new int[max];
}
public void insert(int e)//E e)
{
if(size==max)
{
System.out.println("full");
}
else
{
arr[size++] = e;
heapify(); //
}
}
public void heapify() //heapfiy from down to up
{
int i = size-1;
int parent = (i-1)/2;
while(arr[parent]< arr[i]) //heap max heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void heapify(int index) //heapfiy from down to up //HEAPIFY UP
{
int i = index;
int parent = (i-1)/2;
while(arr[parent]< arr[i]) //heap max heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void delete_max()
{
int maxele=0;
if(size!=0)
{
maxele = arr[0];
arr[0] = arr[size-1]; //copy last emelent to front
if(!(size<=3))
arr[size-1] =-99999;
else
arr[size-1] =-99999;
size--; //ignore last element
}
heapifyDown(); // incomplete code
}
public void heapifyDown() //heapify min heap from root node..after deleteion of root node new lel,ement is root node
{
for(int parent = 0 ; parent< ((size)/2 ) ;parent++) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]> arr[parent] && (arr[left] >=arr[right] || arr[right]==-9999))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left-1; // -1 to compensate parent++ in for loop
}
else if(arr[right]> arr[parent] && (arr[left] <= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right-1; // -1 to compensate parent++ in for loop
}
else
break;
}
}
public void heapifyDown(int index) //heapfiy min heap from a particular index
{
int tempParent = getParent(index);
for(int parent = tempParent ; parent< (size)/2 ;) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]> arr[parent] && (arr[left] >=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left;
}
else if(arr[right]> arr[parent] && (arr[left] <= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right;
}
else
break;
}
}
private int getParent(int index) //get parent index for a child
{
return (index-1)/2;
}
private int right(int index)
{
return (index*2) + 2;
}
private int left(int index)
{
return (index*2) + 1;
}
public boolean isChild(int index)
{
if(index >= ( size/2) +1 )
return true;
else
return false;
}
public void swap(int index1, int index2)
{
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public int extract_max()
{
int max = 0;
if(size!=0)
{
max = arr[0];
}
return max;
}
public void list()
{
for(int i =0 ;i<size;i++)
{
System.out.print(arr[i]);
if(i!=size-1)
{
System.out.print(" ");
}
}
System.out.println("");
}
public void modify(int index, int value)
{
for(int i =0 ;i<size;i++)
{
if(i+1==index)
{
int temp = arr[i];
arr[i]=value;
if(value<temp)
heapifyDown(i);
else if(value>temp)
heapify(i); //smaller value there for heapify up
break;
}
}
}
public int getSmallest(int m) throws NoSmallestElementFound //throws NoSmallestElementFound
{
if(m<=size){
int tsize = size;
int u=0;
int[] q= new int[100];
while(u!=tsize-m)
{
q[u]= extract_max();
u++;
delete_max();
}
int p= extract_max();
for(int k=0;k<u;k++)
insert(q[k]);
return p;
}
else
{
throw new NoSmallestElementFound("No Smallest element found");
}
}
public static void main(String[] args) throws Exception {
PriorityQueue pq = new PriorityQueue();
pq.insert(1);
pq.insert(2);
pq.insert(3);
pq.insert(4);
pq.insert(5);
int s=pq.getSmallest(1);
System.out.println(s);
}
}
------------------------------------Program----------------------------------------------------------------
import java.util.*;
class NoSmallestElementFound extends Exception
{
NoSmallestElementFound(String s)
{
super(s);
}
}
public class PriorityQueue {
int[] arr ;
int size;
int max;
public PriorityQueue()
{
size = 0;
max = 20;
arr = new int[max];
}
public void insert(int e)//E e)
{
if(size==max)
{
System.out.println("full");
}
else
{
arr[size++] = e;
heapify(); //
}
}
public void heapify() //heapfiy from down to up
{
int i = size-1;
int parent = (i-1)/2;
while(arr[parent]< arr[i]) //heap max heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void heapify(int index) //heapfiy from down to up //HEAPIFY UP
{
int i = index;
int parent = (i-1)/2;
while(arr[parent]< arr[i]) //heap max heap
{
int temp = arr[parent];
arr[parent] =arr[i];
arr[i] = temp;
i = parent; //traversing up
parent = (i-1)/2;
}
}
public void delete_max()
{
int maxele=0;
if(size!=0)
{
maxele = arr[0];
arr[0] = arr[size-1]; //copy last emelent to front
if(!(size<=3))
arr[size-1] =-99999;
else
arr[size-1] =-99999;
size--; //ignore last element
}
heapifyDown(); // incomplete code
}
public void heapifyDown() //heapify min heap from root node..after deleteion of root node new lel,ement is root node
{
for(int parent = 0 ; parent< ((size)/2 ) ;parent++) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]> arr[parent] && (arr[left] >=arr[right] || arr[right]==-9999))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left-1; // -1 to compensate parent++ in for loop
}
else if(arr[right]> arr[parent] && (arr[left] <= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right-1; // -1 to compensate parent++ in for loop
}
else
break;
}
}
public void heapifyDown(int index) //heapfiy min heap from a particular index
{
int tempParent = getParent(index);
for(int parent = tempParent ; parent< (size)/2 ;) //only parents
{
int right = parent * 2 +2;
int left = parent *2 +1;
if(arr[left]> arr[parent] && (arr[left] >=arr[right] || arr[right]==0))
{
int temp = arr[left];
arr[left] = arr[parent];
arr[parent] = temp;
parent = left;
}
else if(arr[right]> arr[parent] && (arr[left] <= arr[right] ))
{
int temp = arr[right];
arr[right] = arr[parent];
arr[parent] = temp;
parent = right;
}
else
break;
}
}
private int getParent(int index) //get parent index for a child
{
return (index-1)/2;
}
private int right(int index)
{
return (index*2) + 2;
}
private int left(int index)
{
return (index*2) + 1;
}
public boolean isChild(int index)
{
if(index >= ( size/2) +1 )
return true;
else
return false;
}
public void swap(int index1, int index2)
{
int temp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = temp;
}
public int extract_max()
{
int max = 0;
if(size!=0)
{
max = arr[0];
}
return max;
}
public void list()
{
for(int i =0 ;i<size;i++)
{
System.out.print(arr[i]);
if(i!=size-1)
{
System.out.print(" ");
}
}
System.out.println("");
}
public void modify(int index, int value)
{
for(int i =0 ;i<size;i++)
{
if(i+1==index)
{
int temp = arr[i];
arr[i]=value;
if(value<temp)
heapifyDown(i);
else if(value>temp)
heapify(i); //smaller value there for heapify up
break;
}
}
}
public int getSmallest(int m) throws NoSmallestElementFound //throws NoSmallestElementFound
{
if(m<=size){
int tsize = size;
int u=0;
int[] q= new int[100];
while(u!=tsize-m)
{
q[u]= extract_max();
u++;
delete_max();
}
int p= extract_max();
for(int k=0;k<u;k++)
insert(q[k]);
return p;
}
else
{
throw new NoSmallestElementFound("No Smallest element found");
}
}
public static void main(String[] args) throws Exception {
PriorityQueue pq = new PriorityQueue();
pq.insert(1);
pq.insert(2);
pq.insert(3);
pq.insert(4);
pq.insert(5);
int s=pq.getSmallest(1);
System.out.println(s);
}
}
Subscribe to:
Posts
(
Atom
)