Showing posts with label LOGICAL. Show all posts
Showing posts with label LOGICAL. Show all posts

Monday, 9 August 2021

Fizz Buzz Program in Java (a string representation of numbers from 1 to n)

Problem Statement:

/**
* Fizz Buzz program:
*
* Write a program that outputs the string representation of numbers from 1 to n
*
* But for multiples of three it should output "Fizz" instead of the number &
* for the multiples of five output "Buzz".
*
* For numbers which are multiples of both three and five output
* "FizzBuzz"
*
* For n = 6
*
* create an array of strings like
* [ "1"
* "2"
* "Fizz"
* "4"
* "Buzz"
* "Fizz"
* ]
*
* */
Accepted Program:
package com.algos;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FizzBuzz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
List<String> fbList = new ArrayList<>();
getFizzBuzzStrArray(n, fbList);
for(String fb: fbList) {
System.out.println(fb);
}
}

private static void getFizzBuzzStrArray(int n, List<String> fbList) {
for(int i=1; i<=n; i++)
{
if (i % 3 == 0 && i % 5 == 0) {
fbList.add("FizzBuzz");
continue;
} else if (i % 3 == 0) {
fbList.add("Fizz");
continue;
} else if (i % 5 == 0) {
fbList.add("Buzz");
continue;
} else {
fbList.add(String.valueOf(i));
}
}
}
} 
Output For n=15:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Tuesday, 22 June 2021

Leetcode Solved: Convert a Roman number to Integer

PRODLEM STATEMENT:

For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.


Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII. 
Instead, the number four is written as IV. 
Because the one is before the five we subtract it making four. 
The same principle applies to the number nine, which is written as IX. 
There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.


Example 1:

Input: s = "III"
Output: 3
Example 2:

Input: s = "IV"
Output: 4
Example 3:

Input: s = "IX"
Output: 9
Example 4:

Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.


Constraints:

1 <= s.length <= 15
s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
It is guaranteed that s is a valid roman numeral in the range [1, 3999].
----------------------------------------------------------------------
package com.algos;

import java.util.HashMap;
import java.util.Map;

public class RomanToInteger {

public static void main(String[] args) {
System.out.println(romanToInt("MDCCCLIX")); //XL L X V IV III = 112
}

public static int romanToInt(String s) {
char[] chars = s.toCharArray();
int iCount = 0;
int total = 0;
Map<String, Integer> charMap = new HashMap<>();
charMap.put("I", Integer.valueOf(1));
charMap.put("V", Integer.valueOf(5));
charMap.put("X", Integer.valueOf(10));
charMap.put("L", Integer.valueOf(50));
charMap.put("C", Integer.valueOf(100));
charMap.put("D", Integer.valueOf(500));
charMap.put("M", Integer.valueOf(1000));
char prev = '\0'; // (char) 0
for (int c = chars.length - 1; c >= 0; c--) {
if ('I' == chars[c]) {
iCount++;
if (iCount > 3) {
c--;
break;
} else {
if (prev == 'V' || prev == 'X') {
iCount = 0; //need to verify
total = total - 1;
} else {
total = total + charMap.get("I");
}
prev = chars[c];
if (iCount == 3) {
iCount = 0;
}
continue;
}
} else if ('V' == chars[c]) {
prev = chars[c];
total = total + charMap.get("V");
} else if ('X' == chars[c]) {
if(prev == 'L' || prev == 'C') {
total = total - 10;
} else {
total = total + charMap.get("X");
}
prev = chars[c];
} else if ('L' == chars[c]) {
prev = chars[c];
total = total + charMap.get("L");
} else if ('C' == chars[c]) {
if(prev == 'D' || prev == 'M') {
total = total - 100;
} else {
total = total + charMap.get("C");
}
prev = chars[c];
} else if ('D' == chars[c]) {
prev = chars[c];
total = total + charMap.get("D");
} else if ('M' == chars[c]) {
prev = chars[c];
total = total + charMap.get("M");
}
}
return total;
}
}

Thursday, 10 June 2021

How to reverse the words in a sentence in java ?

Two ways:

> using new StringBuilder().append method
> using apache commons dependence - StringUtils.reverseDelimited(sentence, ' ')
Example:
package com.algos;

public class ReverseSentence {
public static void main(String[] args) {
String sentence = "I am in love with her";
System.out.println("Reverse of a sentence: "
                        + reverseSentence(sentence));
System.out.println(sentence.length() == reverseSentence(sentence).length());
        //2nd way
//By using apache-commons:commons-lang3 dependency
//StringUtils.reverseDelimited(str)
}

private static String reverseSentence(String sentence) {
if (sentence == null) return null;
String[] words = sentence.split(" ");
StringBuilder output = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
output.append(words[i]);
output.append(" ");
}
return output.toString().trim();
}
}

How to reverse the String in java ?

You can use some mutable string related classes like StringBuilder / StringBuffer classes for reversing the string.

> You can use reverse() method of StringBuilder : 
new StringBuilder().reverse for doing this.
> You can also use apache commons dependence - 
& use StringUtils.reverse(String str)
Example:
package com.algos;

public class ReverseString {
public static void main(String[] args) {
String str = "Hello World";
System.out.println("1st Way : Reverse of given string : "
                + reverseStr(str));
        System.out.println("2nd Way : Reverse of given string : " 
                + reverseStr2(str));
//Using 3rd way
//By using apache-commons:commons-lang3
//StringUtils.reverse(str)
}

private static String reverseStr2(String str) {
if (str == null) {
return null;
}
StringBuilder builder = new StringBuilder(str).reverse();
return builder.toString();
}

private static String reverseStr(String str) {
if (str == null) {
return null;
}
char[] in = str.toCharArray();
StringBuilder builder = new StringBuilder();
for (int i = in.length - 1; i >= 0; i--) {
builder.append(in[i]);
}
return builder.toString();
}
}

How to find the missing number from a given array (when only one number is missing from a sequence of non-zero numbers)?

Assumptions :

The array may have only one number missing in the sequence of numbers
with out zero in it.
Example:
int[] arr= {1, 3};
The missing number is 2 (where numbers are from 1 to 3)
Algorithm:
> Calculate the array size, using array size - calculate the sum of n numbers 
(n: array size + 1)
> Traverse the array elements using a for loop - calculate the moving sum
> then after that, diff of number of n numbers - moving sum of elements will 
give the missing number
Example:
package com.algos;

public class OnlyMissingNumberInArray {

public static void main(String[] args) {
int[] arr= {1, 3};
//The missing number from 1 to 3 is 2
System.out.println("The missing number "+ findMissingNumber(arr));
}

private static int findMissingNumber(int[] arr) {
//Calculate sum of numbers from 1 to 3 using n(n+1)/2
int n = arr.length + 1;
int sumOf = n * (n + 1)/2;
int sum = 0;
for(int i : arr) {
sum = sum + i; //moving sum
}
return sumOf - sum; //missing number 2
}
}

Saturday, 14 February 2015

PROGRAM FOR PRINTING ALL PERMUTATIONS OF A STRING - JAVA

Let us say -

String str = "abc"

As the length of the str is 3,  it should have 3! (factorial - 3*2*1) permutations - 6

[abc acb bca bac cab cba]


Example:

It builds all permutations recursively looping through all the characters - char by char

Here I have defined 3 custom methods - All 3 methods are looped after every character.

appendBefore -
appendAfter
appendMiddle

Go Over the code - it is commented properly

If not understood - just try to execute it once
package testing;

import java.util.ArrayList;
import java.util.List;

public class Permutations {

 /*
  * You will get n! (factorial) - permutations from this
  * 
  * Just like this Example: abc (3! = 6 permutations) 
  * [abc acb bac bca cab cbc]
  * 
  */
 static String str = "abcd";
 static char[] ch = str.toCharArray();
 static List s1 = new ArrayList<>();
 static List s2 = new ArrayList<>();

 public static void main(String[] args) {

  // s1 - list stores initial character from the string
  s1.add(String.valueOf(ch[0]));

  // recursive loop - char by char
  for (int k = 1; k < ch.length; k++) {

   // adds char at index 0 for all elements of previous iteration
   appendBefore(s1, ch[k]);
   
   // adds char at last index for all elements of previous iteration
   appendAfter(s1, ch[k]);
   
   /*adds char middle positions like a^b^C - if prev list stores
    * elements whose size() is 3 - then it would have 2 positions fill
    * say d is next char - d should be filled in _^_^_ _ positions are
    * previous permutations for 3 chars a,b,c(i.e 6 permutations
    */
   appendMiddle(s1, ch[k], k);
   
   /*for every iteration first clear s1 - to copy s2, which contains
   previous permutations*/
   s1.clear();
   
   /* now copy s2 to s1- then clear s2
   - this way finally s2 contains all the permutations*/
   for (int x = 0; x < s2.size(); x++) {
    s1.add(s2.get(x));
   }
   //shows how it is building - all iterations
   System.out.println(s1);
   s2.clear();
  }
  System.out.println("Total Permutations for given string "+str+" are "+s1.size());
 }

 private static void appendMiddle(List str, char ch, int positions) {
  for (int pos = 1; pos <= positions - 1; pos++) {
   for (int i = 0; i < str.size(); i++) {
    s2.add(str.get(i).toString().substring(0, pos) 
    + String.valueOf(ch)
    + str.get(i).toString().substring(pos, str.get(i).toString().length()));

   }
  }
 }

 private static void appendBefore(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(String.valueOf(ch) + str.get(i));
  }
 }

 private static void appendAfter(List str, char ch) {
  for (int i = 0; i < str.size(); i++) {
   s2.add(str.get(i) + String.valueOf(ch));
  }
 }

}