Lambda expression quiz - java-8

I have defined a functional interface StringFormatter as below
public interface StringFormatter{
String format(String s1, String s2);
}
How can I write main class which creates lambda expression for above interface and defines format() for below 2 results?
Returns s1 + s2
Returns s1 + "-" + s2

In this case you can easily initialize two variables holding lambda expressions like:
StringFormatter formatter1 = (s1,s2) -> s1 + s2;
StringFormatter formatter2 = (s1,s2) -> s1 + "-" + s2;
Then you can call formatter1.format(s1,s2) and formatter2.format(s1,s2).
Following example:
public class Test {
public interface StringFormatter{
String format(String s1, String s2);
}
public static void main(String[] args) {
final StringFormatter formatter1 = (s1,s2) -> s1 + s2;
final StringFormatter formatter2 = (s1,s2) -> s1 + "-" + s2;
System.out.println(formatter1.format("lorem", "ipsum"));
System.out.println(formatter2.format("lorem", "ipsum"));
}
}
produces output:
loremipsum
lorem-ipsum

We can use a Functional interface as a target type like this:
StringFormatter func = (s1, s2) -> s1 + s2;
in which case you can call it like:
String result = func.format("first","second");
you can also put the logic into a method as such:
static String formatter(StringFormatter func, String s1, String s2){
return func.format(s1, s2);
}
then call it:
String result = formatter((s1, s2) -> s1 + s2, "first", "second");
String anotherResult = formatter((s1, s2) -> s1 +"-"+ s2, "first", "second");
in which case you simply pass the behaviour directly without having to create different inline functions for each scenario.

You might write something like this:
StringFormatter formatter1 = (s1, s2) -> s1 + s2;
StringFormatter formatter2 = (s1, s2) -> s1 + "-" + s2;
Usage:
String result1 = formatter1.format("a", "b"); // ab
String result2 = formatter2.format("a", "b"); // a-b

StringFormatter formatter = (str1,str2) -> str1 + str2;
StringFormatter formatter1 = (str1,str2) -> str1 + "-" + str2;
String formatedString = formatter.format("Hello", "World");
String formatedString1 = formatter1.format("Hello", "World");
System.out.println("Formated String (Type 1) : "+formatedString);
System.out.println("Formated String (Type 2) : "+formatedString1);

Related

How To Count Occurrences Of Each Character In String In Java 8(lambda exp or streams) but not in traditional method?

Sample output All Is Well : { =2, A=1, s=1, e=1, W=1, I=1, l=4}
You may try this,
Arrays.stream("inputstring".split(""))
.map(String::toLowerCase)
.collect(Collectors.groupingBy(s -> s, LinkedHashMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + " = " + v));

Tail recursive solution in Scala for Linked-List chaining

I wanted to write a tail-recursive solution for the following problem on Leetcode -
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contains a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
*Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)*
*Output: 7 -> 0 -> 8*
*Explanation: 342 + 465 = 807.*
Link to the problem on Leetcode
I was not able to figure out a way to call the recursive function in the last line.
What I am trying to achieve here is the recursive calling of the add function that adds the heads of the two lists with a carry and returns a node. The returned node is chained with the node in the calling stack.
I am pretty new to scala, I am guessing I may have missed some useful constructs.
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
import scala.annotation.tailrec
object Solution {
def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {
add(l1, l2, 0)
}
//#tailrec
def add(l1: ListNode, l2: ListNode, carry: Int): ListNode = {
var sum = 0;
sum = (if(l1!=null) l1.x else 0) + (if(l2!=null) l2.x else 0) + carry;
if(l1 != null || l2 != null || sum > 0)
ListNode(sum%10,add(if(l1!=null) l1.next else null, if(l2!=null) l2.next else null,sum/10))
else null;
}
}
You have a couple of problems, which can mostly be reduced as being not idiomatic.
Things like var and null are not common in Scala and usually, you would use a tail-recursive algorithm to avoid that kind of things.
Finally, remember that a tail-recursive algorithm requires that the last expression is either a plain value or a recursive call. For doing that, you usually keep track of the remaining job as well as an accumulator.
Here is a possible solution:
type Digit = Int // Refined [0..9]
type Number = List[Digit] // Refined NonEmpty.
def sum(n1: Number, n2: Number): Number = {
def aux(d1: Digit, d2: Digit, carry: Digit): (Digit, Digit) = {
val tmp = d1 + d2 + carry
val d = tmp % 10
val c = tmp / 10
d -> c
}
#annotation.tailrec
def loop(r1: Number, r2: Number, acc: Number, carry: Digit): Number =
(r1, r2) match {
case (d1 :: tail1, d2 :: tail2) =>
val (d, c) = aux(d1, d2, carry)
loop(r1 = tail1, r2 = tail2, d :: acc, carry = c)
case (Nil, d2 :: tail2) =>
val (d, c) = aux(d1 = 0, d2, carry)
loop(r1 = Nil, r2 = tail2, d :: acc, carry = c)
case (d1 :: tail1, Nil) =>
val (d, c) = aux(d1, d2 = 0, carry)
loop(r1 = tail1, r2 = Nil, d :: acc, carry = c)
case (Nil, Nil) =>
acc
}
loop(r1 = n1, r2 = n2, acc = List.empty, carry = 0).reverse
}
Now, this kind of recursions tends to be very verbose.
Usually, the stdlib provide ways to make this same algorithm more concise:
// This is a solution that do not require the numbers to be already reversed and the output is also in the correct order.
def sum(n1: Number, n2: Number): Number = {
val (result, carry) = n1.reverseIterator.zipAll(n2.reverseIterator, 0, 0).foldLeft(List.empty[Digit] -> 0) {
case ((acc, carry), (d1, d2)) =>
val tmp = d1 + d2 + carry
val d = tmp % 10
val c = tmp / 10
(d :: acc) -> c
}
if (carry > 0) carry :: result else result
}
Scala is less popular on LeetCode, but this Solution (which is not the best) would get accepted by LeetCode's online judge:
import scala.collection.mutable._
object Solution {
def addTwoNumbers(listA: ListNode, listB: ListNode): ListNode = {
var tempBufferA: ListBuffer[Int] = ListBuffer.empty
var tempBufferB: ListBuffer[Int] = ListBuffer.empty
tempBufferA.clear()
tempBufferB.clear()
def listTraversalA(listA: ListNode): ListBuffer[Int] = {
if (listA == null) {
return tempBufferA
} else {
tempBufferA += listA.x
listTraversalA(listA.next)
}
}
def listTraversalB(listB: ListNode): ListBuffer[Int] = {
if (listB == null) {
return tempBufferB
} else {
tempBufferB += listB.x
listTraversalB(listB.next)
}
}
val resultA: ListBuffer[Int] = listTraversalA(listA)
val resultB: ListBuffer[Int] = listTraversalB(listB)
val resultSum: BigInt = BigInt(resultA.reverse.mkString) + BigInt(resultB.reverse.mkString)
var listNodeResult: ListBuffer[ListNode] = ListBuffer.empty
val resultList = resultSum.toString.toList
var lastListNode: ListNode = null
for (i <-0 until resultList.size) {
if (i == 0) {
lastListNode = new ListNode(resultList(i).toString.toInt)
listNodeResult += lastListNode
} else {
lastListNode = new ListNode(resultList(i).toString.toInt, lastListNode)
listNodeResult += lastListNode
}
}
return listNodeResult.reverse(0)
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions, explanations, efficient algorithms with a variety of languages, and time/space complexity analysis in there.

Creating List<Object> inside map

I have string like:
String input = "1 2 20\n"
+ "1 3 50\n"
+ "1 4 40\n"
+ "1 5 30\n"
+ "2 3 20\n"
+ "2 4 40\n"
+ "2 5 30\n"
+ "3 4 50\n"
+ "3 5 60\n"
+ "4 5 70\n";
}
My Nodes Class:
class Nodes{
Integer from;
Integer to;
Integer cost;
}
Corresponding to each String input i want a Nodes object.
SO far I have been able to do like:
List<Nodes> collect = new ArrayList<>();
for loop starts here until the inputs are exhausted.
String[] s = Arrays.stream("1 3 50".split(" ")).toArray(String[]::new);
Nodes nodes = new Nodes(Integer.valueOf(s[0]),Integer.valueOf(s[1]),Integer.valueOf(s[2]));
collect.add(nodes);
for loop ends here
Required output :
List<Nodes>
Is there a way so that I can create a List of Nodes inside stream only like map(h->new Nodes(h[0],h[1],h[2]))and at last collect it using Collectors.toList() so that i have List<Nodes>.
Try this one
List<Nodes> nodes = Arrays.stream(input.split("\\n"))
.map(s->s.split("\\s"))
.map(arr->new Nodes(Integer.valueOf(arr[0]),Integer.valueOf(arr[1]),
Integer.valueOf(arr[2])))
.collect(Collectors.toList());
I would make some modifications to your Nodes class first. Including some error handling in case there is something else than ints in your String. Then stream and collect:
import java.util.List;
import java.util.stream.Collectors;
public class StackOverflowTest {
public static void main(String[] args) {
String input = "1 2 20\n"
+ "1 3 50\n"
+ "1 4 40\n"
+ "1 5 30\n"
+ "2 3 20\n"
+ "2 4 40\n"
+ "2 5 30\n"
+ "3 4 50\n"
+ "3 5 60\n"
+ "4 5 70\n";
List<Nodes> list =
input.lines() // streaming each line
.map(s -> new Nodes(s.split(" "))) // creating Nodes
.collect(Collectors.toList()); // Collecting to List
System.out.println(list);
}
}
class Nodes{
Integer from;
Integer to;
Integer cost;
Nodes(String[] strings) {
this(stringToInts(strings)); // avoid throwing error in constructor
}
Nodes(int[] ints) {
this.from = ints[0];
this.to = ints[1];
this.cost = ints[2];
}
public String toString() {
return "Nodes:from=" + from + ".to=" + to + ".cost=" + cost + "\n";
}
private static int[] stringToInts(String[] strings) {
if (strings.length != 3) throw new AssertionError("String array of wrong size. Must be 3");
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
return ints;
}
}
On reflection the exeption handling can also be achieved just by adding
.map(arr-> {if (arr.length != 3) throw new AssertionError("Array size != 3"); return arr;})
to the Answer by Hadi J
I don't code java but in python there's a function called list() that converts string to lists and maybe there is one on java too.
or maybe use split(", ") and maybe it will work.

Generate all valid combinations of N pairs of parentheses

UPDATE (task detailed Explanation):
We have a string consist of numbers 0 and 1, divided by operators |, ^ or &. The task is to create all fully parenthesized expressions. So the final expressions should be divided into "2 parts"
For example
0^1 -> (0)^(1) but not extraneously: 0^1 -> (((0))^(1))
Example for expression 1|0&1:
(1)|((0)&(1))
((1)|(0))&(1)
As you can see both expressions above have left and write part:
left: (1); right: ((0)&(1))
left: ((1)|(0)); right: (1)
I tried the following code, but it does not work correctly (see output):
// expression has type string
// result has type Array (ArrayList in Java)
function setParens(expression, result) {
if (expression.length === 1) return "(" + expression + ")";
for (var i = 0; i < expression.length; i++) {
var c = expression[i];
if (c === "|" || c === "^" || c === "&") {
var left = expression.substring(0, i);
var right = expression.substring(i + 1);
leftParen = setParens(left, result);
rightParen = setParens(right, result);
var newExp = leftParen + c + rightParen;
result.push(newExp);
}
}
return expression;
}
function test() {
var r = [];
setParens('1|0&1', r);
console.log(r);
}
test();
code output: ["(0)&(1)", "(0)|0&1", "(1)|(0)", "1|0&(1)"]
Assuming the input expression is not already partially parenthesized and you want only fully parenthesized results:
FullyParenthesize(expression[1...n])
result = {}
// looking for operators
for p = 1 to n do
// binary operator; parenthesize LHS and RHS
// parenthesize the binary operation
if expression[p] is a binary operator then
lps = FullyParenthesize(expression[1 ... p - 1])
rps = FullyParenthesize(expression[p + 1 ... n])
for each lp in lps do
for each rp in rps do
result = result U {"(" + lp + expression[p] + rp + ")"}
// no binary operations <=> single variable
if result == {} then
result = {"(" + expression + ")")}
return result
Example: 1|2&3
FullyParenthesize("1|2&3")
result = {}
binary operator | at p = 2;
lps = FullyParenthesize("1")
no operators
result = {"(" + "1" + ")"}
return result = {"(1)"}
rps = Parenthesize("2&3")
result = {"2&3", "(2&3)"}
binary operator & at p = 2
lps = Parenthesize("2")
no operators
result = {"(" + "2" + ")"}
return result = {"(2)"}
rps = Parenthesize("3")
no operators
result = {"(" + "3" + ")"}
return result = {"(3)"}
lp = "(2)"
rp = "(3)"
result = result U {"(" + "(2)" + "&" + "(3)" + ")"}
return result = {"((2)&(3))"}
lp = "(1)"
rp = "((2)&(3))"
result = result U {"(" + "(1)" + "|" + "((2)&(3))" + ")"}
binary operator & at p = 4
...
result = result U {"(" + "((1)|(2))" + "&" + "(3)" + ")"}
return result {"((1)|((2)&(3)))", "(((1)|(2))&(3))"}
You will have 2^k unique fully parenthesized expressions (without repeated parentheses) given an input expression with k binary operators.

How to construct an array in ATS?

For instance, how can I construct an array in ATS containing all of the letters in the upper case from A to Z? In C, this can be done as follows:
char *Letters()
{
int i;
char *cs = (char *)malloc(26);
assert(cs != 0);
for (i = 0; i < 26; i += 1) cs[i] = 'A' + i;
return cs;
}
You could use the tabulate function for creating linear arrays. For instance,
extern
fun
Letters(): arrayptr(char, 26)
implement
Letters() =
arrayptr_tabulate_cloref<char>
(i2sz(26), lam(i) => 'A' + sz2i(i))
If you don't want to use a higher-order function, you can try the following template-based solutioin:
implement
Letters() =
arrayptr_tabulate<char>(i2sz(26)) where
{
implement array_tabulate$fopr<char> (i) = 'A' + sz2i(i)
}
Well, here's one way, although it's extremely complicated, because it follows your outlined approach to the letter: it involves linear proofs for arrays (aka dataviews), memory allocation, and array initialization via a while loop.
extern
fun
Letters (): arrayptr (char, 26)
implement
Letters () = let
val (pf_arr, pf_gc | p_arr) = array_ptr_alloc<char> ((i2sz)26)
var i: int = 0
prval [larr:addr] EQADDR () = eqaddr_make_ptr (p_arr)
var p = p_arr
prvar pf0 = array_v_nil {char} ()
prvar pf1 = pf_arr
//
val () =
while* {i:nat | i <= 26} .<26-i>. (
i: int (i)
, p: ptr (larr + i*sizeof(char))
, pf0: array_v (char, larr, i)
, pf1: array_v (char?, larr+i*sizeof(char), 26-i)
) : (
pf0: array_v (char, larr, 26)
, pf1: array_v (char?, larr+i*sizeof(char), 0)
) => (
i < 26
) {
//
prval (pf_at, pf1_res) = array_v_uncons {char?} (pf1)
prval () = pf1 := pf1_res
//
val c = 'A' + (g0ofg1)i
val () = ptr_set<char> (pf_at | p, c)
val () = p := ptr1_succ<char> (p)
//
prval () = pf0 := array_v_extend {char} (pf0, pf_at)
val () = i := i + 1
//
} // end of [val]
//
prval () = pf_arr := pf0
prval () = array_v_unnil {char?} (pf1)
//
val res = arrayptr_encode (pf_arr, pf_gc | p_arr)
in
res
end // end of [Letters]
You can run the code at Glot.io

Resources