Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Sunday, 14 November 2021

Factorial of any number in Java 8 - using reduction

Reduction - will reduce a stream of values to a result by using an identity (may be an initial value) and a function that will be applied internally on that stream. This processing may not be sequentially, its parallel stream.

import java.util.stream.LongStream;


public class Factorial {
public static void main(String[] args) {
    System.out.println(facto(5));
}

public static int facto(int n){
return IntStream.rangeClosed(1, n)
.reduce(1, (int a, int b) -> a * b);
}
}
we can either use LongStream or IntStream. 
LongStream.rangeClosed(1, n) gives stream of values from 1 to n, 
n is included here.
if you want to exclude nth value, 
you can use
LongStream.range(1, n) gives stream of values from 1 to n-1.
reduce function will apply a function a*b with 1 as initial value
 (also known as identity)
Its the similar operation as the following code.
long result = identity;
* for (long element : this stream)
* result = accumulator.applyAsLong(result, element)
* return result;
But the above code performs the same operation in sequential manner, 
but the reduce will apply the function in parallel form.

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

Thursday, 24 June 2021

How to read your tweets, create a tweet & publish in Java using twitter4j-stream api ?

Firstly, you need to create an app in https://apps.twitter.com using a developer account in Twitter. During this process, if you are doing this for first time, you may need to sign up in this & then create an app. 

To further explain this, actually Twitter provides OAuth credentials to this app, using those OAuth credentials, your app can successfully login to tied up Twitter account, then it can post, read & any other such Twitter operations can be done by app on behalf of the actual Twitter account. It works like, your app acts as client app with Twitter as OAuth provider. Just like any other OAuth Client with a OAuth Provider. A typical OAuth flow.

After creating an app in above mentioned link, you need to set the permissions for your app - if you want only read the tweets - A read-only permission would be enough. Otherwise if you want to tweet (post a tweet) from you app, you need to give write permissions as well.

The same link apps.twitter.com  gives you these four important OAuth related information, which you will read & configure in you application (java application).

OAuth Consumer Key:  <Some alphanumeric key>

[Recognises you app as a consumer]

OAuth Consumer Secret:  <Some alphanumeric key>

[represents your app secret]

OAuth Access Token:  <Some alphanumeric key>

[Recognises Access Token - valid for some time - only - you can revoke this token & regenerate - whenever you like to]

OAuth Access Token Secret:  <Some alphanumeric key>

[Recognises Access Token Secret]

NOTE: Keep these credentials in secret configuration locations like VAULT.

Dependencies Required: twitter4j-stream

Gradle:

implementation group: 'org.twitter4j', name: 'twitter4j-stream', version: '4.0.7'
Add the above dependencies in your build.gradle (or if your are using maven, 
pls form the maven config as similar to the above groupid & artefact)
-----------------------------------------------------------------------------
package com.basic.twitter;

import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterDemo {
public static void main(String[] args) throws TwitterException {
Twitter twitter = getTwitterInstance();
readTweets(twitter);
String message
            = "I am writing this tweet from my Java IDE using twitter4j-stream";
sendTweet(twitter, message);
}

private static void sendTweet(Twitter twitter, String message)
               throws TwitterException {
Status status = twitter.updateStatus(message);
System.out.println(status.getRetweetCount()); //checking any retweet count
}


private static void readTweets(Twitter twitter) throws TwitterException {
ResponseList<Status> messages = twitter.getHomeTimeline();
messages.stream().map(m -> m.getText()).forEach(message -> {
System.out.println(message);
System.out.println("--------------------------------\n");
});
}

private static Twitter getTwitterInstance() {
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder
.setOAuthConsumerKey("<<Your OAuth Consumer Key>>")
.setOAuthConsumerSecret("<<Your OAuth Consumer Secret>>")
.setOAuthAccessToken("<<Your OAuth Access Token>>")
.setOAuthAccessTokenSecret("<<Your OAuth Token Secret>>");

TwitterFactory twitterFactory
                    = new TwitterFactory(configurationBuilder.build());
return twitterFactory.getInstance();
}
}

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;
}
}

Friday, 18 June 2021

How to check whether a given number is Armstrong Number or not?

What is an Armstrong Number?

An Armstrong Number is a number, where the sum of cubes of each digit of that 
number is equal to the given number.
Example: 371 = 33 + 73 + 13
----------------------------------------------------------------------------------------------------------------------
package com.algos;

import java.util.Scanner;

public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(checkArmstrongNumber(n));
}

private static boolean checkArmstrongNumber(int n) {
int movingCubeTot = 0;
int temp = n;
while(temp > 0) {
int currDig = temp % 10;
temp = temp/10;
movingCubeTot = movingCubeTot + (currDig * currDig * currDig);
}
return n == movingCubeTot;
}
}

Thursday, 10 June 2021

How to print the date in specific format in java?

You can format the dates in java using SimpleDateFormat class from java.text pacakge.

Create an object of SimpleDateFormat - provide the pattern to constructor.
Note: Pattern will have date specific literals.

String pattern = "yy-MM-dd";

SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);

For example: 

package com.algos;

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormat {
public static void main(String[] args) {
String pattern = "dd-MM-yy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
System.out.println(dateFormat.format(new Date()));
}
}

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
}
}