Showing posts with label sumith puri. Show all posts
Showing posts with label sumith puri. Show all posts

Wednesday, December 8, 2021

SKP's Java Problem Solving Series : Van Eck's Sequence (Naive & Fast Lookup)

[Question/Problem Statement is from GeeksforGeeks]

Algorithms/Data Structures - [Problem Solving] 
Given a Positive Integer N, The Task is to Print N Terms of the Van Eck’s Sequence. In Maths, Van Eck’s sequence is an Integer Sequence which is defined recursively as given below.    
-
-
 Let the First Term Be 0 i.e, a[0] = 0.
 Then for n>=0, If There Exists an m<n, such that a[m] = a[n]
 -
 Take the Largest such m and set a[n+1] = [n − m];
 Otherwise a[n+1] = 0, Start with a(1) = 0.
 
Example

[ First Few Terms of Van Eck’s Sequence are as Follows: ] 

0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5 …
 

Constraints
• [No Special Constraints Exist]


Input Format
[N is a Constant in the Java Code, For Example N=50]
 
 
Sample Output (Each Should Be on a Separate Line)
0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5, 3, 0, 3, 2, 9, 0, 4, 9, 3, 6, 14, 0, 6, 3, 5, 15, 0, 5, 3, 5, 2, 17, 0, 6, 11, 0, 3, 8, 0, 3, 3,
  
______________ 
 
 
 
/**
 * The Mathematical Puzzle of Van Eck's Sequence - Xebia Interview - 07-Dec-2021
 * [At the Experience Level of 17y - Was Interviewing for Java/Java EE Architect]
 */

// Given a Positive Integer N, The Task is to Print Nth Term of the Van Eck’s Sequence.
// In Maths, Van Eck’s sequence is an Integer Sequence which is defined Recursively As: 
//   
// Let the First Term Be 0 i.e, a[0] = 0.
// Then for n>=0, If There Exists an m<n 
// such that a[m] = a[n]
// -
// Take the Largest such m and set a[n+1] = [n − m];
// Otherwise a[n+1] = 0, Start with a(1) = 0.
// -  
// [ First Few Terms of Van Eck’s Sequence are as Follows: ] 
//  
// 0, 0, 1, 0, 2, 0, 2, 2, 1, 6, 0, 5, 0, 2, 6, 5, 4, 0, 5 … 
//  
// Input: N = 05, Output: 2
//  
// Input: N = 10, Output: 6 


/**
 * @author sumith.puri
 *
 */
public class VanEckSequence {

  static final int N=50;
  
  int[] printSeq    = null;
  int[] index1      = null;
  int val           = 0;
  int index         = 3;
 


  VanEckSequence() {

    init();
  }


  private void init() {

    printSeq    = new int[50];
    index1      = new int[200];
    val         = 0;
    index       = 3;
    index1[val] = 1;
  }


  public void linearVanEckSequence() {
    for (int i = 2; i < N; i++) {

      for (int j = i - 1; j > 0; j--) {
        if (printSeq[i - 1] == printSeq[j - 1]) {

          printSeq[index - 1] = i - j;          
          break;
        }
      }
      index++;
    }
  }


  public void fasterVanEckSequence() {
    
    int i = 0;
    
    for (int j = 2; j < N; j++) {

      i = j - 1;
      val = printSeq[i];

      // System.out.println("index:" + index + ":"+ val);
      if (index1[val] == 0) {

        printSeq[index-1] = 0;
        index1[val] = i + 1;
      } else {
        printSeq[index-1] = (i + 1) - index1[val];
        // optimal - fast lookup
        index1[val] = (i + 1);
      }
      index++;
    }
  }



  /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub


    VanEckSequence vancEckSequence = new VanEckSequence();
    vancEckSequence.linearVanEckSequence();

    System.out.println("Van Eck Sequence (Linear/Naive Algorithm)");
    System.out.println("----------------------------------------)");
    for (int i = 0; i < N; i++) {

      System.out.print(vancEckSequence.printSeq[i] + ", ");
    }

    System.out.println("\n");
    vancEckSequence.init();
    vancEckSequence.fasterVanEckSequence();

    System.out.println("Van Eck Sequence (Fast Lookup Algorithm)");
    System.out.println("----------------------------------------)");


    for (int i = 0; i < N; i++) {

      System.out.print(vancEckSequence.printSeq[i] + ", ");
    }

    System.out.println("");
    System.out.println("\n");
    System.out.println("Sumith Kumar Puri");
    System.out.println("SCJP 1.4, SCJP 5.0 / SCBCD 1.4, SCBCD 5.0");
    System.out.println("BB Spring 2.x, Hibernate 3.x, Java EE 6.x");
    System.out.println("Quest C, Quest C++, Quest Data Structures");
    System.out.println("Google India Code Jam 2005 Semi-Finalist.");
    System.out.println("Techgig Code Gladiators '15 Semi-Finalist");
    System.out.println("Societe Generale Brainwaves '15 Finalist.");
    System.out.println("Mphasis (Internal) Hackathon - Rank#7/106");
    System.out.println("Java Code Geeks, DZone MVB* & DZone Core*");
    System.out.println("Senior Member, ACM & Senior Member, IEEE.");
    System.out.println("Member*, CSI*; Foojay.IO & Developer.com*");
  }

}

Friday, February 12, 2021

SKP's Java Problem Solving Series : Usernames Changes (HackerRank)

[Question/Problem Statement is Adapted from HackerRank]

Algorithms/Data Structures - [Problem Solving] 
There is a Specific Need for Changes in a List of Usernames. In a given List of Usernames - For Each Username - If the Username can be Modified and Moved Ahead in a Dictionary. The Allowed Modification is that Alphabets can change Positions in the Given Username.

Example
usernames[] = {"Aab", "Cat"}
 
"Aab" cannot be changed to another unique string matching the above rule - Hence, It can Never Find a Place Ahead in the Dictionary. Hence, Output will be "NO". "Cat" can be Changed to "Act", "Atc", "Tca", "Tac", "Cta" and Definitely "Act" will Find a Place Before "Cat" in the Dictionary. Hence, Output will be "YES".

[Function Description]
Complete the function possibleChanges in the Editor Below.
 
possibleChanges has the Following Parameters:
String usernames[n]: An Array of User Names
 
Returns String[n]: An Array with "YES" or "NO" Based on Feasibility
(Actual Question Says String Array, But Signature is List of Strings)


Constraints
• [No Special Constraints Exist, But Cannot Recall Exactly]


Input Format

"The First Line Contains an Integer, n, the Number of Elements in Usernames.", 
"Each Line of the n Subsequent Lines (where 0 < i < n) contains a String usernames[i]."        

[Sample Case 0 - Sample Input For Custom Testing]        
8      
Aab 
Cat
Pqrs
Buba
Bapg
Sungi
Lapg
Acba
       

Sample Output (Each Should Be on a Separate Line)
NO YES NO YES YES YES YES YES
  
______________ 
 
 
[Explanation of the Solution]
This is again a Good Question from Hacker Rank to Test Your Logic / Problem Solving Abilities. The Core Point to Handle is that For Each Combination of 2 Alphabets that Exists in the Username String > We Need to Check if the Latter Occuring Character (ASCII) is Less than the Former Occuring Character (ASCII). For Example in the String "Bapg" - For a Selection of "Ba" from "Bapg" - We have "a" Occuring Before "B" in the English Alphabet. We can Have Two Loops (One Nested) to Decide for a Combination of Each Two Alphabets. The Time Complexity of this Solution is O(n^2).
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

/*
* HackerRank Problem Solving - Speak Ur Mind, But Ride a Fast Horse.
* ~ Sumith Kumar Puri (c) 2021 ~ -- ~ Bengaluru, Karnataka, India ~
*
*/
class UsernamesChangesLogic {

public static List<String> possibleChanges(List<String> usernames) {

List<String> solutionStr = new ArrayList<String>();
boolean bobbysFlag = false;
for (String username : usernames) {

bobbysFlag = false;
String currName = username.toLowerCase();
for (int i = 0; i < currName.length(); i++) {

int a = currName.charAt(i);
for (int j = i + 1; j < currName.length(); j++) {

int b = currName.charAt(j);
if (b < a) {
bobbysFlag = true;
break;
}
}
if (bobbysFlag) {
solutionStr.add("YES");
break;
}
}
if (!bobbysFlag)
solutionStr.add("NO");
}

return solutionStr;
}
}

public class UsernamesChanges {

public static final String OUTPUT_PATH = "PROVIDE_ABSOLUTE_INPUT_FILE_NAME";

public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(OUTPUT_PATH));

int usernamesCount = Integer.parseInt(bufferedReader.readLine().trim());

List<String> usernames = IntStream.range(0, usernamesCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());

List<String> result = UsernamesChangesLogic.possibleChanges(usernames);

bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

bufferedReader.close();
bufferedWriter.close();
}
}

Happy Problem Solving using Java!

SKP's Java Problem Solving Series : Active Traders (HackerRank)

[Question/Problem Statement is the Property of HackerRank]

Algorithms/Data Structures - [Problem Solving] 
An Institutional Broker wants to Review their Book of Customers to see which are Most Acctive. Given a List of Trades By "Customer Name, Determine which Customers Account for At Least 5% of the Total Number of Trades. Order the List Alphabetically Ascending By Name."


Example
n = 23
"customers = {"Bigcorp", "Bigcorp", "Acme", "Bigcorp", "Zork", "Zork", "Abe", "Bigcorp",  "Acme", "Bigcorp", "Bigcorp" , "Zork", "Bigcorp", "Zork", "Zork", "Bigcorp", "Acme", "Bigcorp", "Acme", "Bigcorp", "Acme",""Littlecorp" , "Nadircorp "}."


"Bigcorp had 10 Trades out of 23,which is 43.48% of the Total Trades."

"Both Acme and Zork had 5 trades,which is 21.74% of the Total Trades."

"The Littlecorp, Nadircorp and Abe had 1 Trade Each, which is 4.35%..."

"So the Answer is [""Acme"", "" Bigcorp  ,""Zork""] (In Alphabetical Order) Because only These Three Companies Placed atleast 5% of the Trades.


Function Description

Complete the Function mostActive in the Editor Below.

mostActive
has the following parameter:
String customers[n] : An Array Customer Names

(Actual Question Says String Array, But Signature is List of Strings)

Returns String[] : An Alphabetically Ascending Array


Constraints

• 1 < n < 10^5

• 1 < Length of customers[] < 20

• The First Character of customers[i] is a Capital English letter.

• All Characters of customers[i] except for the First One are Lowercase.

• Guaranteed that At least One Customer makes atleast 5% of Trades.



Input Format
            

"The First Line contains an integer, n, The Number of Elements in customers."       

"Each Line iof the n Subsequent Lines (where 0 s i< n) contains a string, customers[i]."      


Sample Case 0 Input For Custom Testing
20       

Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Alpha Omega Beta      


Function mostActive      
customers[] size n =  20       

customers[] = [As Provided Above]       



Sample Output

Alpha       

Beta

Omega       



Explanation

"Alpha made 10 Trades out of 20 (50% of the Total), Omega made 9 Trades (45% of the Total). and Beta made 1 Trade (5% of the Total).All of them have met the 5% Threshold, so all the Strings are Returned in an Alphabetically Ordered Array."        

 
______________ 
 
 
[Explanation of the Solution]
This is Good Practice for the Brain for Problem Solving - Involves Simple Arithmetic and Mathematical Application. Ideally, A Programmer would want to Optimize the Solution in Space and Time (Which I Did Not :-)
 
________________  
 

[Source Code, Sumith Puri (c) 2021 - Free to Use & Distribute]
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.IntStream;

/*
* HackerRank Problem Solving - Ain't a Horse that Can't be Rode
* Sumith Kumar Puri (c) 2021 - ~ Bengaluru, Karnataka, India ~
*
*/
class ActiveTradersLogic {

public static List<String> mostActive(List<String> customers) {

// How About Arrays or Custom LinkedList for a 'Very Fast' Traversal?
Map<String, Integer> customerMap = new TreeMap<String, Integer>();
List<String> solutionStr = new ArrayList<String>();
int customerMapSize = customers.size();

for (int i = 0; i < customerMapSize; i++) {

String customerKey = customers.get(i);

if (customerMap.containsKey(customerKey)) {

Integer customerCount = customerMap.get(customerKey);
customerMap.put(customerKey, ++customerCount);
} else {
customerMap.put(customerKey, 1);
}
}

Set<String> customerMapKeys = customerMap.keySet();
for (String customerKey : customerMapKeys) {

Integer customerCount = customerMap.get(customerKey);
double currentCustomerPercent = (double) (customerCount) / (double) customerMapSize;

if (currentCustomerPercent * 100 >= 5.0) {

solutionStr.add(customerKey);
}
}

return solutionStr;
}
}

public class ActiveTraders {

public static final String OUTPUT_PATH = "PROVIDE_ABSOLUTE_INPUT_FILE_NAME";

public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv(OUTPUT_PATH)));

int customersCount = Integer.parseInt(bufferedReader.readLine().trim());

List<String> customers = IntStream.range(0, customersCount).mapToObj(i -> {
try {
return bufferedReader.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}).collect(toList());

List<String> result = ActiveTradersLogic.mostActive(customers);

bufferedWriter.write(result.stream().collect(joining("\n")) + "\n");

bufferedReader.close();
bufferedWriter.close();
}
}

Happy Problem Solving using Java!

Thursday, February 6, 2020

Elevated to the Elite Developers/Contributors List! ;-)

All Blog Followers, Random Visitors, Developers, Contributors => Take Note.

My Blog / I Got [Promoted / Elevated] to DZone Core! The Elite Developers/Contributors List on Planet Earth!  Spent Decent Enough Time - About ~17+ Years Now => Championing, Evangelizing, Learning, Teaching, Applying, Prototyping, Building, [Doing], Glorifying Core Java and Jakarta EE ;-)  Primarily I am a Backend (Presentation, Business/Service, Web Services/Integration, Persistence, Database) Developer or Architect. [Feb 2020] Right Now, I am Employed as a Senior Product Development Manager at Ultria Software Private Limited, Bengaluru, Karnataka, India.

By the Way, I hold 7 Certifications* in Core Java/Java EE, 3 in C/CPP/Data Structures => Also, I am a Java Code Geek; Senior Member, ACM; Senior Member, IEEE;

Thanks, DZone [Blake Ethridge].

 
 

Friday, August 29, 2008

Techila Shots!

Well, That's a Catchy Name... You'd be Thinking! This wasn't a Very Well Thought out Title or One that Required a Christening Ceremony. Had It in My Mind for a Few Years > Tried Implementing it as a Weekly Technical Talk Series in an Organization, As Well.

So, What is Techila Shots?
Techila Shots is a Measure of Techie Talk Delivered with a Dash of Passion and a Slice of Experience, that Gives a Kick to my Developer Psyche (What a Pitch?). It is a Forum that Presents my Thoughts on Technical Topics that I am most Enthusiastic About. Mostly, It is about the Geek in me. Hope that Someone Reading It will Find it at the Least Helpful, If Not as Much to Deliver a Kick!
 
 
[Above Post was Written at the Start of this Blog > 29th August, 2008 - Written from my Rental Apartment at Washington Building, Deals Gateway, Deptford, London SE13 7SE, United Kingdom - Was in London, UK for ~1 Year under the Highly Skilled Migrant Programme (HSMP) Visa]
 

 
[Update : On 03rd September, 2020 from my Own Apartment at C2-2010, VBHC Palm Haven 2, Doddabele, Kengeri Hobli, Bengaluru 560060, Karnataka, India - Take a Note of of All the Blog Recognitions / Engineering Recognitions that I Have Received From August 2008 - August 2020]

Java Code Geek Program (JCG)
DZone Most Valuable Blogger (MVB)
DZone Core (Promoted)
Member, Computer Society of India*
Senior Member, IEEE (Elevated)
Senior Member, ACM (Elevated)

For the First 3, The Main Criteria was my Blog and for the Last 2, One of the Important Input was my Leadership as a Technical Blogger.