23 Aralık 2019 Pazartesi

Java Page Turning Question

Brie’s Drawing teacher asks her class to open their books to a page number. Brie can either start turning pages from the front of the book or from the back of the book. She always turns pages one at a time. When she opens the book, page  is always on the right side:
image
When she flips page , she sees pages  and . Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is  pages long, and she wants to turn to page , what is the minimum number of pages she will turn? She can start at the beginning or the end of the book.
Given  and , find and print the minimum number of pages Brie must turn in order to arrive at page .
Function Description
Complete the pageCount function in the editor below. It should return the minimum number of pages Brie must turn.
pageCount has the following parameter(s):
  • n: the number of pages in the book
  • p: the page number to turn to
Input Format
The first line contains an integer , the number of pages in the book.
The second line contains an integer, , the page that Brie's teacher wants her to turn to.

Sample Input 0
6
2
Sample Output 0
1
Explanation 0
If Brie starts turning from page , she only needs to turn  page:
Untitled Diagram(6).png
If Brie starts turning from page , she needs to turn  pages:
Untitled Diagram(3).png
Because we want to print the minumum number of page turns, we print  as our answer.
Sample Input 1
5
4
Sample Output 1
0
Explanation 1
If Brie starts turning from page , she needs to turn  pages:
Untitled Diagram(4).png
If Brie starts turning from page , she doesn't need to turn any pages:
Untitled Diagram(5).png
Because we want to print the minimum number of page turns, we print  as our answer.

Cozum : 
total = n/2
right = p/2
left = total - right
min (right, left)

static int pageCount(int n, int p) {
/*
* Write your code here.
*/
return Math.min(p/2, n/2 - p/2);

}

22 Aralık 2019 Pazar

Java Sorting

ID, FirstName, and CGPA bilgileri olan student listesi verilmis olsun. Bizim amacimiz CGPA lerini azalan sirada siralamak. Eger 2 ogrencinin CGPA leri esitse o zaman firstnamelerini alfabetik siraya gore siralayalim. Eger ayni isimlere sahiplerse ID lerine gore siralayalim. Her ogrencinin farkli ID si oldugu icin sorun olmaz. 
Ornek Input 

5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75

22 Fahim 3.76

Output

Ashis
Fahim
Samara
Samiha

Rumpa

Burada 5 kac tane input olacagi.

Bu soruya asagidaki koddaki boslugu tamamlayalim.

import java.util.*;
class Student{
 private int id;
 private String fname;
 private double cgpa;
 public Student(int id, String fname, double cgpa) {
  super();
  this.id = id;
  this.fname = fname;
  this.cgpa = cgpa;
 }
 public int getId() {
  return id;
 }
 public String getFname() {
  return fname;
 }
 public double getCgpa() {
  return cgpa;
 }
}

//Complete the code
public class Solution
{
 public static void main(String[] args){
  Scanner in = new Scanner(System.in);
  int testCases = Integer.parseInt(in.nextLine());
  
  List studentList = new ArrayList();
  while(testCases>0){
   int id = in.nextInt();
   String fname = in.next();
   double cgpa = in.nextDouble();
   
   Student st = new Student(id, fname, cgpa);
   studentList.add(st);
   
   testCases--;
  }
      
        Collections.sort(studentList, Comparator.comparing(Student :: getCgpa).reversed().
              thenComparing(Student :: getFname).thenComparing(Student :: getId)); 

       for(Student st: studentList){
   System.out.println(st.getFname());
  }
 }
}

1 Aralık 2019 Pazar

K - Largest Element of Array

Asagidaki soruda yapmamiz istenen verilen arraydaki k largest elementi bulmak.

Ornegin

arr[] = [3, 2, 1, 5, 6, 4], ve k =2 icin once siralayalim

1 2 3 4 5 6. burdaki en buyuk 2. eleman 5 oldugu icin output 5 olmalidir.

Cozume gecelim.

Nasil cozeriz :
 Once siralariz. Sonra da sondan k. elemani buluruz.

import java.util.Arrays;
import java.util.PriorityQueue;
public class KLargestElement {
 public static int kLargest(int[] arr, int k) {
  Arrays.sort(arr);
  return arr[arr.length - k];  
 } 
 public static void main(String[] args) {
  int arr[] = new int[] {3, 2, 1, 5, 6, 4};
  System.out.println(kLargest(arr, 2));
  
  int arr2[] = new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6};
  System.out.println(kLargest(arr2, 4));
 }
}

Burda once siraladik sonra da sondan k. elemani bulduk. Islemin time completixy si O(nlogn) dir. Cunku siralama yaptigimiz icin .

Daha effektif yapmaya calisalim. Bunun icin heap kullanalim.

Elemanlari tek tek heap e eklerken, eger heap in size i k den buyukse ilk elemani cikaralim. Bu sekilde yaptigimizda elimizde en son k eleman kalmis olur. Bizde ilk elemani dondurursek o eleman k largest elemanimiz olur.

import java.util.Arrays;
import java.util.PriorityQueue;
public class KLargestElement {
 public static int kLargest(int[] arr, int k) {
  PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
  for(int num : arr) {
    minHeap.add(num);
    if(minHeap.size() > k) {
     minHeap.remove();
    }
  }
  return minHeap.remove();
 } 
 public static void main(String[] args) {
  int arr[] = new int[] {3, 2, 1, 5, 6, 4};
  System.out.println(kLargest(arr, 2));
         int arr2[] = new int[] {3, 2, 3, 1, 2, 4, 5, 5, 6};
  System.out.println(kLargest(arr2, 4));
 }
}

Burada array i sort etmiyoruz. Heap kullaniyoruz. Burda ise time O(n) dir.

Validate String with Paranthesis

Verilen string imizde acilan parantezlerin sirayla kapanip kapanmadigini kontrol etmek istiyoruz.

Ornegin:

abc(){}[] => bu bizim gecerlidir. cunku acilan parantezler sirayla kapanmistir.

({)} => Bu ise gecersizdir. cunku { kapanmadan ( kapanmis.

Bunun icin izlememiz gereken yol su olmalidir.

Oncelikle acik parantezlerin ne oldugunu bir set te tanimladim ki o anki characterimin acik parantez oldugunu kontrol edebileyim. Eger acik parantezse bunu stack e ekliyorum. (Bu sekilde en son hangi parantez acildi kontrol edebilecegim)

Daha sonra kapali parantezler ve onlarin acik karsiliklarini bir mapte tanimliyorum. Bu sekilde eger o anki elemanim kapali parantezse bunun acik karsiligini buluyorum, ve stackteki son elemanla karsilastiriyorum. ornegin o anki elemanim ] ise bunun acik karsiligini mapten [ olarak buldum. Simdi ise stack in en ustundeki elemani pop ediyorum. [ mu diye kontrol ediyorum, eger degilse duzgun kapanmamistir. false dondurup bitiriyorum.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class ValidateParanthesisString {

 public static boolean isValidParanthesis(String str) {
  Map<Character, Character> closedMap = new HashMap();
  
  closedMap.put(')', '(');
  closedMap.put('}', '{');
  closedMap.put(']', '[');
  
  Set<Character> openParanthesis = new HashSet();
  openParanthesis.add('{');
  openParanthesis.add('[');
  openParanthesis.add('(');
  Stack<Character> openParanthesisStack = new Stack();
  
  for(int i=0; i< str.length(); i++) {
   if(openParanthesis.contains(str.charAt(i))) {
    openParanthesisStack.push(str.charAt(i));
   }
   if(closedMap.containsKey(str.charAt(i))) {
    if(!openParanthesisStack.pop().equals(closedMap.get(str.charAt(i)))) {
     return false;
    }
   }
  }
  return true;  
 } 
 public static void main(String[] args) {
  String str = "({)}";
  System.out.println(isValidParanthesis(str));
  String str2 = "abc() {}[]";
  System.out.println(isValidParanthesis(str2));
 }
}

Output: false true


Common Element of Three Array in Java

Elimizde 3 tane array olsun ve bunlardaki ortak elemanlari bulmak isteyelim.

Input
arr1 = [2, 6, 9, 11, 13, 17]
arr2 = [3, 6, 7, 10, 13, 18]
arr3 = [4, 5, 6, 9,  11,  13]

Output: [6, 13]

Burda izleyecegimiz yol soyle olmali:

x: arr1 in o anki elemani
y: arr2 nin o anki elemani
z: arr3 un o anki elemani

x,y ve z esit mi diye kontrol edecegiz. esitlerse arraya o anki elemani eklicez. ve herbirini 1 arttircaz
eger x, yden kucukse xi bir sonraki elemana atayacagiz.
y, zden kucukse y yi bir sonraki elemana atayacagiz
hic biri degilse zyi bir sonraki elemana atayacagiz


import java.util.ArrayList;
import java.util.List;
public class FindIntersection {
 public static List<Integer> intersection(int[] arr1, int[] arr2, int[] arr3) {
  List<Integer> commonElements = new ArrayList<Integer>();
  int x = 0, y = 0, z = 0;
  while (x < arr1.length && y < arr1.length && z < arr1.length) {
   if (arr1[x] == arr2[y] && arr1[x] == arr3[z]) {
    commonElements.add(arr1[x]);
    x++;
    y++;
    z++;
   } else {
    if (arr1[x] < arr2[y]) {
     x++;
    } else if (arr2[y] < arr3[z]) {
     y++;
    } else {
     z++;
    }
   }
  }
  return commonElements;
 }
 public static void main(String[] args) {
  int arr1[] = new int[] { 2, 6, 9, 11, 13, 17 };
  int arr2[] = new int[] { 3, 6, 7, 10, 13, 18 };
  int arr3[] = new int[] { 4, 5, 6, 9, 11, 13 };

  System.out.println(intersection(arr1, arr2, arr3));
 }
}