Posts

Showing posts from March, 2021

Codechef : Program to find if given very large number is divisible by 3 or not

Image
Multiple of 3 Problem Code: MULTHREE Consider a very long  K -digit number  N  with digits  d 0 , d 1 , ..., d K-1  (in decimal notation;  d 0  is the most significant and  d K-1  the least significant digit). This number is so large that we can't give it to you on the input explicitly; instead, you are only given its starting digits and a way to construct the remainder of the number. Specifically, you are given  d 0  and  d 1 ; for each  i  ≥ 2,  d i  is the sum of all preceding (more significant) digits, modulo 10 — more formally, the following formula must hold:  Determine if  N  is a multiple of 3. Example 3 5 3 4 13 8 1 760399384224 5 1 NO YES YES Java Solution : //codechef very very long number Multiple of three // https://www.codechef.com/LRNDSA01/problems/MULTHREE ...

Maze Traveller Problem solved using Dynamic programming

Image
 Maze Traveller Solution in Java solved using recursion. import java.util.*; class mazeTraveller { static HashMap<String, Long> map = new HashMap<>(); static long calculate(int row , int col) { return _calculate(row, col , map); } static long _calculate(int row ,int col,HashMap<String,Long> map) { String key = row+":"+col; if(map.containsKey(key)) return map.get(key); if(row == 0 || col == 0 ) return 0; if(col == 1 || row == 1) return 1; long res = _calculate(row-1,col,map) + _calculate(row,col-1,map); map.put(key,res); return map.get(key); } static Scanner input = new Scanner(System.in); public static void main(String[] args) { try { int row = input.nextInt(); int col = input.nextInt(); long paths = calculate(row,col); System.out.println("There are "+paths ...

ThreeSum Solution in Java

Image
ThreeSum in java. Given an array nums of n integers , are there elements a , b , c in nums such that a + b + c = 0 Find all unique triplets in the array which gives the sum of zero. Note the solution set must not contain duplicate triplets. Example : Given array nums = [ -1 , 0 , 1 , 2 , -1 , -4 ] A solution set is : [ [-1 , 0 , 1], [ -1, -1, 2], ] import java.util.*; class ThreeSum { static List<List<Integer>> calculate(int[] arr) { if(arr == null || arr.length < 3) { return Collections.emptyList(); } int n = arr.length; List<List<Integer>> list = new ArrayList<List<Integer>>(); Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<n-2;i++) { int first = arr[i]; for(int j=i+1;j<n;j++) { int remain = first+arr[j]; remain = (remain<0)?Ma...

TwoSum Solution in Java

Image
 Two sum solution in Java . Question : Given an array of integers nums and an integer target , return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.  Input  : nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. import java.util.*; class TwoSum { static int[] calculate(int[] arr , int target) { Map<Integer,Integer> map = new HashMap<>(); for(int i=0;i<arr.length;i++) { int remain = target - arr[i]; if(map.containsKey(remain)) { return new int[] {map.get(remain),i}; } map.put(arr[i],i); // System.out.println(map); } throw new IllegalArgumentException("No two sum solution"); } pu...

Todays Challange :

Image
 Solved Challange : Java Code :   import java.util.*; class Temp { static void add(String[] ans , String str, int index) { ans[index] = str; } static Scanner input = new Scanner(System.in); public static void main(String[] args) { try { int n = input.nextInt(); String[] ans = new String[n]; String s = ""; int first = 0; int last = n-1; int flag = 0; for(int i=1;i<= n*n;i++) { if(i%n==0){ s += "" +i; if(flag == 0) { flag = 1; add(ans,s,first++); } else{ flag = 0; add(ans,s,last--); } s = ""; continue; } s+= "" + i + "*"; } for(String sss:ans) System.out.println(sss); } catch(Exception e){ ...

Find all array elements occurring more than ⌊N/3⌋ times.

Image
  Q. Find all array elements occurring more than ⌊N/3⌋ times. Solution in java : // find elements in the array that occurs more than n/3 times in array // 19 march 2021 // T.U.F Question import java.util.*; class cf { static void calc(int[] arr ) { int len = arr.length; //first solution // HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); // for(int i=0;i<len;i++) { // if(!map.containsKey(arr[i])){ // map.put(arr[i],1); // } // else{ // map.put(arr[i],map.get(arr[i])+1); // } // } // System.out.println(map); // map.forEach((key,value)-> { // if(value>len/3) // System.out.println(key); // }); int cnt1 = 0; int cnt2 = 0; int num1 = -1; int num2 = -1; for(int i=0;i<len;i++) { if(arr[i] == num1){ cnt1++; } else if(arr[i] == num2){ ...

Simple Socket Programming in java

Image
 In this Java network programming tutorial, you will learn how to develop a simple socket server program. Server.java package simple_tcp; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Server { public Server() throws Exception { ServerSocket server_socket = new ServerSocket(2020); //opening a new port System.out.println("Port 2020 is open."); Socket socket = server_socket.accept(); System.out.println("Client " + socket.getInetAddress() + " has connected."); // I/O buffers: BufferedReader in_socket = new BufferedReader(new InputStreamReader (socket.getInputStream())); PrintWriter out_socket = new PrintWriter(new OutputStreamWriter (socket.getOutputStream()), true); out_socket.println("Welcome!...

Family Tree Project in Java

Image
Creating Family tree in java .  Trees are such an important structure in computer science. But what more important tree, than our family tree? ❤️   👨‍👩‍👧‍👦   ❤️    Made this simple program in java to implement family tree. Java File import java.util.*; class Person { String name; boolean married; String wife; int noOfChild; Person[] childs; public Person(String name){ this.name = name; } public Person(String name,boolean married,String wife,Person[] childs,int noOfChild) { this.name = name; this.married = married; this.wife = wife; this.childs = childs; this.noOfChild = noOfChild; } public Person(String name , boolean married,String wife) { this.name = name; this.married = married; this.wife = wife; } } class familyTree { static int population; static Scanner input = new Scanner...

How to take input from user in sublime 3 in JavaScript? [ SOLVED ]

Image
 [SOLVED] Take console (cmd) input in sublime 3 text editor in javascript Open Sublime  goto   >   Tools   >  Build System   >  Build New System       paste the following code in that file and save it as  anyName.sublime-build { "cmd":["start", "cmd", "/k" ,"node","$file_base_name"], "selector": "source.jW", "working_dir": "${file_path}", "shell": true } And now in your js file add these lines. Help from official website : click here const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }) readline.question(`What's your name?`, name => { console.log(`Hi ${name}!`) readline.close() })

How to find Max and Min value in array java.

Image
Finding min or max value in premative array import java.util.*; class cf { static Scanner input = new Scanner(System.in); public static void main(String[] args) { Integer[] arr = {2,3,1,5,3,61,12}; int max = Collections.max(Arrays.asList(arr)); int min = Collections.min(Arrays.asList(arr)); System.out.println(max); System.out.println(min); } } Output : 61 1

Java Factorial Using BigInteger

Image
Solving Factorial of number by using BigInteger in Java import java.util.*; import java.math.BigInteger; class cf { static HashMap<BigInteger,BigInteger> list = new HashMap<>(); static BigInteger extraLongFactorials(int n) { BigInteger N = new BigInteger(String.valueOf(n)); if(list.containsKey(N)) return list.get(N); if(n==1 || n==2 || n==0) return N; else { BigInteger ans = N.multiply(extraLongFactorials(n-1)); list.put(N,ans); return list.get(N); } } static Scanner input = new Scanner(System.in); public static void main(String[] args) { try { int n = input.nextInt(); System.out.println(extraLongFactorials(n)); } catch(Exception e){ return; } } } Output : 100 9332621544394415268169923885626670049071596826438162146859296389521759999322991560894146397...

java:17: error: local variables referenced from a lambda expression must be final or effectively final count ++ ;

Image
 Modifying variables inside java lambdas. Integer list[] = {1,2,3,4,5,6,7,8}; int index = 0; Arrays.asList(list).forEach(e -> { System.out.println(e+" at index "+index); index++; }); Error : maze2.java:22: error: local variables referenced from a lambda expression must be final or effectively final System.out.println(e+" at index "+index); ^ maze2.java:23: error: local variables referenced from a lambda expression must be final or effectively final index++; ^ Solution : Integer list[] = {1,2,3,4,5,6,7,8}; int[] index = {0}; Arrays.asList(list).forEach(e -> { System.out.println(e+" at index "+index[0]); index[0]++; }); Output : 1 at index 0 2 at index 1 3 at index 2 4 at index 3 5 at index 4 6 at index 5 7 at index 6 8 at index 7

Maze Solver in Java. (some part incomplete)

Image
 Maze Solver program in Java.  import java.util.*; import java.io.*; class maze2 { static Scanner input = new Scanner(System.in); public static void main(String[] args) { Integer arr[][] = {{0,0,0,0,9}, {1,0,0,1,0},              {0,1,1,0,0}, {1,0,1,1,1}, {8,0,0,0,0}}; int size = arr.length*arr[0].length; ArrayList<ArrayList<Integer>> maze = new ArrayList<ArrayList<Integer>>(size); int[] index = {0}; Arrays.asList(arr).forEach(row -> { maze.add(new ArrayList<Integer>()); Arrays.asList(row).forEach(item -> maze.get(index[0]).add(item)); index[0]++; }); Graph graph = new Graph(size,maze); // System.out.println(maze); System.out.println("\ndfs"); graph.dfs(20,4); } } class Graph { int V ; int start , end ; ArrayList<ArrayList<Integer>> list = n...

Graph Implementation in java Bfs and Dfs

Image
Graph Data Structure implementation in java import java.util.*; class Graph { ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); int V; public Graph(int v){ this.V = v; for(int i=0;i<V;i++) list.add(new ArrayList<Integer>()); } void add(int s , int d){ list.get(s).add(d); list.get(d).add(s); } void display(){ for(int i=0;i<V;i++){ System.out.print(i+" : "); for(int x : list.get(i)) System.out.print(" => "+x); System.out.println(""); } } void dfs(int start){ boolean visited[] = new boolean[V]; _dfs(start,visited); } void _dfs(int node , boolean[] visited){ visited[node] = true; System.out.print(node+" => "); for(int x : list.get(node)){ if(!visited[x]){ _dfs(x,visited); } } } void bfs(int start){ boolean visited[] = new boolean[V]; Queue<Integer> q = new LinkedList<Integer>(); q.add(start); vis...
Image
Java program to List all files in a directory and nested sub-directories import java.io.*; import java.util.*; class solution { static void yRec(File[] arr,int index , int level){ if(index==arr.length ) return; for(int i=0;i level;i++) System.out.print("\t"); if(arr[index].isFile()) { System.out.println("File : "+arr[index].getName()+" of size : "+arr[index].length()+" bytes"); } else if(arr[index].isDirectory()){ File[] subArr = arr[index].listFiles(); if(subArr.length == 0) return; System.out.println("[" + arr[index].getName() + "]" + " has "+subArr.length+" files. Path : "+subArr[0].getParent()); yRec(subArr,0,level+1); } yRec(arr,++index,level); } public static void main(String[] args) { String path = "D:\\web\\assets\\fonts"; // String path = args[0...

Graph in Java

Solving Graph in Java import java.util.*; class Graph { LinkedList list[] ; public Graph(int V){ list = new LinkedList[V]; for(int i=0;i V;i++) list[i] = new LinkedList (); } void addEdge(int source , int destination){ list[source].add(destination); list[destination].add(source); } public int bfs(int source , int destination){ boolean visited[] = new boolean[list.length]; int parent[] = new int[list.length]; Queue q = new LinkedList (); q.add(source); parent[source] = -1; visited[source] = true; while(!q.isEmpty()){ int curr = q.poll(); if(curr == destination) break; for(int neighbor : list[curr]){ if(!visited[neighbor]){ visited[neighbor] = true; q.add(neighbor); parent[neighbor] = curr; } } } int cur = destination; int distance = 0; while(parent[cur] != -1) { ...

Another Binary Tree

import java.util.*; class solution { static Scanner input = new Scanner(System.in); static Node createTree(){ Node root = null; System.out.println("Enter Data : "); int data = input.nextInt(); if(data == -1) return root; root = new Node(data); System.out.println("Enter to left of "+data); root.left = createTree(); System.out.println("Enter to right of "+data); root.right = createTree(); return root; } static void inOrder(Node root){ if(root == null) return; inOrder(root.left); System.out.println(root.data+"=>"); inOrder(root.right); } static void postOrder(Node root){ if(root == null) return; postOrder(root.left); postOrder(root.right); System.out.println(root.data+"=>"); } static void preOrder(Node root){ if(root == null) return; System.out.println(root.data+"=...

Binary Tree

My Program to create Binary Tree and print sorted output class Node { int data ; Node left,right; Node(int value) { this.data = value; left = null; right = null; } } class myTree { Node root ; myTree () { root = null ; } // apending to tree void add(int value) { if(root==null) { root = new Node(value); System.out.println("Root created = "+root.data); return; } _add(root,value); } void _add(Node pointer, int value) { if(pointer.data < value) { if(pointer.right != null) { _add(pointer.right , value); } else { pointer.right = new Node(value); System.out.println("Inserted "+pointer.right.data+" to right of "...

My Bad Code

I wrote this code for codechef march 2021 contest for "college life 4" problem but was unsucessfull to solve it Link of the problem here This is for the futute me. Try to solve this problem if you think you are smart import java.util.*; import java.util.stream.*; import java.io.*; class multiMap { long key; long value; multiMap(long key,long value){ this.key = key; this.value = value; } void display(){ System.out.println("key : "+key+"\t value : "+value); } } class MyList{ List keyMapList = new ArrayList (); public MyList(long a , long b,long c,long A,long B,long C){ keyMapList.add(new multiMap(a,A)); keyMapList.add(new multiMap(b,B)); keyMapList.add(new multiMap(c,C)); keyMapList = keyMapList.stream().sorted(Comparator.comparing(e->e.key)).collect(Collectors.toList()); } void pop(){ keyMapList.remove(0); } long getValue(long index){ return keyMapList.get((int)index).value; } long getKey(){ return keyMapList.get...

Popular Posts

java:17: error: local variables referenced from a lambda expression must be final or effectively final count ++ ;

Family Tree Project in Java

Creating basic tic tac toe android app using java