Skip to main content

merge sort

0 likes • Nov 18, 2022 • 0 views
Java
Loading...

More Java Posts

LeetCode #21: Merge Two Sorted Lists

0 likes • Oct 15, 2022 • 0 views
Java
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode handler = head;
while(l1 != null && l2 != null) {
if (l1.val <= l2.val) {
handler.next = l1;
l1 = l1.next;
} else {
handler.next = l2;
l2 = l2.next;
}
handler = handler.next;
}
if (l1 != null) {
handler.next = l1;
} else if (l2 != null) {
handler.next = l2;
}
return head.next;
}
}

Heap sort

0 likes • Nov 19, 2022 • 0 views
Java
import java.util.*;
public class HeapSortMain {
public static void buildheap(int []arr) {
/*
* As last non leaf node will be at (arr.length-1)/2
* so we will start from this location for heapifying the elements
* */
for(int i=(arr.length-1)/2; i>=0; i--){
heapify(arr,i,arr.length-1);
}
}
public static void heapify(int[] arr, int i,int size) {
int left = 2*i+1;
int right = 2*i+2;
int max;
if(left <= size && arr[left] > arr[i]){
max=left;
} else {
max=i;
}
if(right <= size && arr[right] > arr[max]) {
max=right;
}
// If max is not current node, exchange it with max of left and right child
if(max!=i) {
exchange(arr,i, max);
heapify(arr, max,size);
}
}
public static void exchange(int[] arr,int i, int j) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public static int[] heapSort(int[] arr) {
buildheap(arr);
int sizeOfHeap=arr.length-1;
for(int i=sizeOfHeap; i>0; i--) {
exchange(arr,0, i);
sizeOfHeap=sizeOfHeap-1;
heapify(arr, 0,sizeOfHeap);
}
return arr;
}
public static void main(String[] args) {
int[] arr={1,10,16,19,3,5};
System.out.println("Before Heap Sort : ");
System.out.println(Arrays.toString(arr));
arr=heapSort(arr);
System.out.println("=====================");
System.out.println("After Heap Sort : ");
System.out.println(Arrays.toString(arr));
}
}

try-catch modularity

0 likes • Jan 31, 2023 • 0 views
Java
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getUserById(long id) {
try {
return userRepository.getUserById(id);
} catch (Exception e) {
// Log the exception here
System.out.println("An error occurred while fetching the user: " + e.getMessage());
return null;
}
}
}
public class UserRepository {
public User getUserById(long id) throws Exception {
// Database query to fetch the user
if (id < 0) {
throw new Exception("Invalid user id");
}
// Return the user object
return new User(id, "John Doe");
}
}
public class User {
private long id;
private String name;
public User(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
}

Send Email from Java

0 likes • Nov 19, 2022 • 3 views
Java
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
{
boolean debug = false;
//Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
}

WordleSolver

0 likes • Feb 1, 2022 • 1 view
Java
//Leif Messinger
//Solves wordle
//Needs a list of wordle words, newline separated and 5 characters each
import java.util.*;
import java.io.File;
import java.io.FileNotFoundException;
class WordleSolver {
public static void printPointer(int position){
for(int i = 0; i < position; ++i){
System.out.print(" ");
}
System.out.print("^");
}
public static void main(String[] args) throws FileNotFoundException{
if(args.length < 1) return;
File dictionary = new File(args[0]);
Scanner sc = new Scanner(dictionary);
ArrayList<String> possibleWords = new ArrayList<String>();
while(sc.hasNextLine()){
possibleWords.add(sc.nextLine());
}
Scanner input = new Scanner(System.in);
while(possibleWords.size() > 0){
//Choose a word out of the possible words
final int randomIndex = (int)(Math.random() * possibleWords.size());
String chosenWord = possibleWords.get(randomIndex);
possibleWords.remove(randomIndex);
System.out.println("Is it correct?");
for(int i = 0; i < chosenWord.length(); ++i){
System.out.println(chosenWord);
printPointer(i);
System.out.println(" y/n?");
if(input.nextLine().toLowerCase().contains("y")){
//Filter by correct character
for(int possibleWord = possibleWords.size() - 1; possibleWord >= 0; --possibleWord){ //Has to be backwards for removing entries, also has to be int not unsigned
if(possibleWords.get(possibleWord).charAt(i) != chosenWord.charAt(i)){
possibleWords.remove(possibleWord);
}
}
}
}
System.out.println("Is it misplaced?");
//Stores a count of every letter misplaced
short[] misplacedCounts = new short[('z'-'a')+1]; //Praise be the garbage collector
for(int i = 0; i < chosenWord.length(); ++i){
System.out.println(chosenWord);
printPointer(i);
System.out.println(" y/n?");
if(input.nextLine().toLowerCase().contains("y")){
//Filter to make sure there's at least as many letters as needed
++misplacedCounts[(chosenWord.charAt(i) - 'a') - 1];
for(int possibleWord = possibleWords.size() - 1; possibleWord >= 0; --possibleWord){ //Has to be backwards for removing entries, also has to be int not unsigned
int count = 0;
for(int j = 0; j < possibleWords.get(possibleWord).length(); ++j){
if(possibleWords.get(possibleWord).charAt(j) == chosenWord.charAt(i))
++count;
}
//If there's not enough of the character that we need, then we remove that from the list of possible characters
if(count < misplacedCounts[(chosenWord.charAt(i) - 'a') - 1]){
possibleWords.remove(possibleWord);
}
}
//Also filter out words where that letter doesn't belong there
for(int possibleWord = possibleWords.size() - 1; possibleWord >= 0; --possibleWord){ //Has to be backwards for removing entries, also has to be int not unsigned
if(possibleWords.get(possibleWord).charAt(i) == chosenWord.charAt(i)){
possibleWords.remove(possibleWord);
continue; //Breaks the current word and moves on in the loop
}
}
}
}
}
}
}

quick sort

0 likes • Nov 19, 2022 • 0 views
Java
import java.util.Arrays;
public class QuickSortMain {
private static int array[];
public static void sort(int[] arr) {
if (arr == null || arr.length == 0) {
return;
}
array = arr;
quickSort(0, array.length-1);
}
private static void quickSort(int left, int right) {
int i = left;
int j = right;
// find pivot number, we will take it as mid
int pivot = array[left+(right-left)/2];
while (i <= j) {
/**
* In each iteration, we will increment left until we find element greater than pivot
* We will decrement right until we find element less than pivot
*/
while (array[i] < pivot) { i++; } while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchange(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (left < j)
quickSort(left, j);
if (i < right)
quickSort(i, right);
}
private static void exchange(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[]){
int[] input = {33,21,45,64,55,34,11,8,3,5,1};
System.out.println("Before Sorting : ");
System.out.println(Arrays.toString(input));
sort(input);
System.out.println("==================");
System.out.println("After Sorting : ");
System.out.println(Arrays.toString(array));
}
}