PeyarTheriyaa
BAN USERif the sub tree has zero coins in the node that means we have to bring one coin to that node essentially meaning deficit of (i.e. 1 of) coins be it deficit or surplus the coin needs to be moved so 1 requires 1 move
 PeyarTheriyaa April 14, 2019something like this should be ok
public static void main(String[] args) {
var input = new Scanner(System.in);
System.out.print("Enter number <0 to exit> : ");
var n = input.nextInt();
while (n != 0) {
System.out.println(isHappy(n) ? 1 : 0);
System.out.print("Enter number <0 to exit> : ");
n = input.nextInt();
}
}
private static boolean isHappy(int n) {
var set = new HashSet<Integer>();
int computed;
do {
computed = 0;
set.add(n);
while (n > 0) {
computed += square(n % 10);
n /= 10;
}
if (set.contains(computed)) break;
n = computed;
} while (computed != 1);
return computed == 1;
}
private static int square(int i) { return i * i; }

PeyarTheriyaa
March 20, 2019 Ok mate seems like this is what you are looking for
int main(int argc, char const *argv[])
{
int n = 0;
printf("Enter Size N : ");
scanf("%d", &n);
int a[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
{
printf("Enter A[%2d][%2d] : ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
int si = 0, sj = 0, ei = n  1, ej = n  1;
int direction = 0;
while (si < ei  sj < ej)
{
switch (direction % 4)
{
case 0: sj++; break;
case 1: ei; break;
case 2: ej; break;
case 3: si++; break;
}
direction++;
}
printf("the last element is %d", a[si][sj]);
return 0;
}
based on the direction it keeps removing one row or column to get to the central element
 PeyarTheriyaa March 15, 2019do you want something like this?
1234

567 8
  
9 1011 12
 
13141516
where the last number is 10?
 PeyarTheriyaa March 13, 2019This is how I'd do it, inspiration leetcode 459
private static String FindPattern(String input) throws NoSuchObjectException {
int repeatPos=(input+input).indexOf(input,1);
if (repeatPos==1)
throw new NoSuchObjectException("Pattern not found!!!");
else
return input.substring(0,repeatPos);
}

PeyarTheriyaa
March 07, 2019 In c
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdbool.h>
char set[10];
int end;
void combinations(char *num, char *pre, int curr, int lvl)
{
if (curr < strlen(num))
{
if (num[curr] >= '0' && num[curr] <= '9')
{
pre[lvl] = num[curr];
combinations(num, pre, curr + 1, lvl + 1);
}
else if (num[curr] == '$')
for (int i = 0; i < end; i++)
{
pre[lvl] = set[i];
combinations(num, pre, curr + 1, lvl + 1);
}
else
combinations(num, pre, curr + 1, lvl);
}
else
{
pre[lvl] = '\0';
printf("%s\n", pre);
}
}
int main(int argc, char const *argv[])
{
char num[20], pre[20];
printf("Enter Number String : ");
scanf("%s", num);
end = 0;
for (int i = 0; i < strlen(num); i++)
if (num[i] >= '0' && num[i] <= '9')
{
bool flag = true;
for (int j = 0; j < end; j++)
if (set[j] == num[i])
flag = false;
if (flag == true)
set[end++] = num[i];
}
combinations(num, pre, 0, 0);
return 0;
}

PeyarTheriyaa
March 01, 2019 rewrote in c check that answer
 PeyarTheriyaa March 01, 2019this how I'd solve the problem
class Scratch {
private static ArrayList<Character> num;
public static void main(String[] args) {
System.out.print("Enter he number string : ");
String input = (new Scanner(System.in)).next();
num = new ArrayList<>();
for (char c : input.toCharArray())
if (c >= '0' && c <= '9') num.add(c);
combinations(input, "", 0);
}
private static void combinations(String input, String pre, int i) {
if (i < input.length()) {
char c = input.charAt(i);
if (c >= '0' && c <= '9')
combinations(input, pre + c, i + 1);
if (c == '$')
for (char t : num)
combinations(input, pre + t, i + 1);
}
else System.out.println(pre);
}
}

PeyarTheriyaa
February 26, 2019 something like this would be sufficient
while (retry < MAX_RETRY) {
if (istream.hasNext()) {
// read stream
retry = 0;
} else {
sleep(1000);
retry++;
}
}
your logic for checking if the input is present might be different
but the general concept should be similar
I kinda did it using Kotlin, but Java should be really similar,
order the countries in descending by no of players
for K slots fill each country in one slot where the min total players is the lowest
(when the no of total players in slot clashes no of countries in the slot must be lowest)
this should give us minimum difference between the slots and the max number of teams is the min total of the slots
import java.util.*
import kotlin.collections.ArrayList
private val input = Scanner(System.`in`)
fun main(args: Array<String>) {
print("Enter no of countries N : ")
val n = input.nextInt()
val arr = ArrayList<Int>()
repeat(n) { i >
print("Enter count of Players of Country[${i + 1}] : ")
arr.add(input.nextInt())
}
arr.sortDescending()
print("Enter size of Team K : ")
val k = input.nextInt()
val slots = ArrayList<Slots>()
repeat(k) { slots.add(Slots()) }
arr.forEach {
slots.sortedBy { it.sArr.size }
.sortedByDescending { it.total }
.minBy { it.total }?.apply {
total += it
sArr.add(it)
}
}
print("Max possible No of teams is ${slots.minBy { it.total }?.total}")
}
class Slots(var total: Int = 0, val sArr: ArrayList<Int> = ArrayList())

PeyarTheriyaa
February 14, 2019 This is how I'd do it for Node with val and kids
if t1.val == t2.val match t2.kids in t1.kids is even one not found return false
else match t2 in t1.kids
boolean match(Node t1, Node t2) {
boolean ret = false;
if (t1.val == t2.val) {
ret = true; // true if no kids for t1 and t2
for (Node item : t2.kids) {
ret = false; // false if t2 has kids but t1 doesn't have one of t2.kids
for (Node other : t1.kids)
ret = match(other, item);
if (!ret) break;
}
return ret;
}
for (Node other : t1.kids)
ret = match(other, t2);
return ret;
}
I couldn't test it, so do post if this works for you
 PeyarTheriyaa February 11, 2019its an (n log(n)) solution assumes 2 things
1 need to use up all the money
2 can come back to the beginning of the shops if there is a balance of money
but to my knowledge this might be the optimal solution
Something like this would go well,(Java)
private static int calculate(int amount, int[] q, int[] c) {
int ret = 0;
int bal = 0;
for (int i = 0; i < n; i++) {
int n = amount / c[i];
int quantity = q[i] * n;
if (quantity > ret) {
ret = quantity;
bal = amount % c[i];
}
}
if (ret!=0&&bal!=0) ret+=calculate(bal,q,c);
return ret;
}

PeyarTheriyaa
January 24, 2019 the root function does the same as s**1/2or3or4(python) in java there is no direct function to do so had to implement it in code
 PeyarTheriyaa January 15, 2019if we need to include for all solutions in 0 to s then we need to add not just 1 per a we find, we need to add 1 for each 0 to a for every a we find i.e. a+1 to count.
the only place were this might be false is when a>10000 in that case we need to add 10001 to count
the modified code will be this
if (a > 1) {
System.out.println("a=0to" + a + " b=" + b + " c=" + c + " d=" + d);
count += Math.min(a + 1, 10001);
}

PeyarTheriyaa
January 14, 2019 i redid the solution please check the other answer
 PeyarTheriyaa January 14, 2019I redid the solution... now the O(n^3)
Optimizations
1 like that of @hrabryi found the limits for c, b, d dynamically (improvement in best case Ω and average case Θ, but not in worst case O, still O(n^4))
2 did away with looping a from 0 to 10000 since we can assume that a from calculating
a = s(b^2 + c^3 + d^4)
and we can check if for given b, c, d inferred a is in 0 to 10000
this gives us O(n^3) the solution is as follows
public static void main(String[] args) {
System.out.print("Enter the value s (0<=s<=10^15) : ");
long s = (new Scanner(System.in)).nextLong();
System.out.println("The count of integrals is " + countOfIntegrals(s));
}
private static long countOfIntegrals(long s) {
long count = 0;
long lb, lc, ld, cp3, dp4;
ld = Math.min(root(s, 4), 10000);
for (int d = 0; d <= ld; d++) {
dp4 = pow(d, 4);
lc = Math.min(root(s  dp4, 3), 10000);
for (int c = 0; c <= lc; c++) {
cp3 = pow(c, 3);
lb = Math.min(root(s  dp4  cp3, 2), 10000);
for (int b = 0; b <= lb; b++) {
long a = s  (pow(b, 2) + cp3 + dp4);
if (a < 10001 && a > 1) {
System.out.println(a + " " + b + " " + c + " " + d);
count++;
}
}
}
}
return count;
}
private static long pow(int n, int p) {
return p > 1 ? n * pow(n, p  1) : n;
}
private static long root(long s, int pow) {
return (long) Math.floor(Math.exp(Math.log(s) / pow)) + 1;
}
other smaller optimizations only to adjust working code for java
 PeyarTheriyaa January 14, 2019four for loops is being used and so the complexity is still O(n^4)...
 PeyarTheriyaa January 14, 2019something like this should work but note that the time complexity is O(n^4)
public static void main(String[] args) {
System.out.print("Enter the value s (0<=s<=10^15) : ");
long s = (new Scanner(System.in)).nextLong();
System.out.println("The count of integrals is " + countOfIntegrals(s));
}
private static long countOfIntegrals(long s) {
long count = 0, pb2, pc3;
int a, b, c, d;
for (a = 0; a <= s && a < 10001; a++)
for (b = 0, pb2 = a + pow(b, 2); pb2 <= s && b < 10001; pb2 = a + pow(++b, 2))
for (c = 0, pc3 = pb2 + pow(c, 3); pc3 <= s && c < 10001; pc3 = pb2 + pow(++c, 3))
for (d = 0; d < 10001; d++)
if (pc3 + pow(d, 4) == s) {
System.out.println(a + " " + b + " " + c + " " + d);
count++;
break;
}
return count;
}
private static long pow(int n, int p) {
return p > 1 ? n * pow(n, p  1) : n;
}

PeyarTheriyaa
January 13, 2019 I'd do something like this,
class Node {
int num;
HashSet<Node> next = new HashSet<>();
}
boolean allPathsConnect(Node curr, HashSet<Node> visited, Node end) {
if (curr == end) return true;
if (visited.contains(curr)) return true;
else if (curr.next.isEmpty()) return false;
else {
visited.add(curr);
for (Node i : curr.next) {
if (!allPathsConnect(i, visited, end)) return false;
}
return true;
}
}

PeyarTheriyaa
January 03, 2019 Pass the result variable to the function?
like this
void mul(int *a, int *b, int *ans)
{
*ans = *a * *b;
}
int main(int argc, char const *argv[])
{
int a = 5;
int b = 4;
int ans;
mul(&a, &b, &ans);
printf("%d * %d = %d\n", a, b, ans);
return 0;
}

PeyarTheriyaa
December 23, 2018 I'd do something like this
int n=0xDA;
int filter = 0x10;
if (n&filter==0) printf("Zero");
else printf("One");

PeyarTheriyaa
December 23, 2018 Here's what I'd do
for position
1 loop min from pos to 0(array index 1) and stop when array[min] becomes greater than array[pos](our given num) this will be the index at which our condition breaks so min+1 is in range where array[pos] is the largest num in range
2 similarly loop max from pos to array length, so when our condition breaks max1 will contain the pos of the last number thats smaller than our given num
3 convert into our range that will be in [1 to array size] from machine index which will be in [0 to array size 1] by adding 1 to min+1 and max1... which is min+2 and max
heres how the program goes
static int[] arr = {1, 5, 4, 3, 6};
public static void main(String[] args) {
for (int i = 0; i < arr.length; i++) {
printREIsMax(i);
}
}
private static void printREIsMax(int pos) {
int min = pos, max = pos;
while (min >= 0 && arr[min] <= arr[pos]) min;
while (max < arr.length && arr[max] <= arr[pos]) max++;
System.out.println(arr[pos] + "[" + (min + 2) + "," + (max) + "]");
}

PeyarTheriyaa
December 12, 2018 no reason you can use 'while' or 'for' even... just a thought process glitch
 PeyarTheriyaa December 11, 2018I kinda built a binary tree out of an array and use that to print sorted values
#include <stdio.h>
int arr[100], end = 0;
void insert(int index, int v)
{
int tmp, i;
for (i = index; i < end; i++)
{
tmp = arr[i];
arr[i] = v;
v = tmp;
}
arr[end] = v;
end++;
}
void add(int s, int e, int v)
{
if (s == e)
insert(s, v);
else
{
int mid = (e + s) / 2;
if (arr[mid] == v)
insert(mid, v);
else if (arr[mid] > v)
add(s, mid, v);
else
add(mid + 1, e, v);
}
}
void printAsc()
{
for (int i = 0; i < end; i++)
printf("%d ", arr[i]);
}
void printDes()
{
for (int i = end  1; i >= 0; i)
printf("%d ", arr[i]);
}
int main(int argc, char const *argv[])
{
int n, tmp;
printf("Enter the limit n : ");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("Enter number %d : ", i + 1);
scanf("%d", &tmp);
add(0, end, tmp);
}
printf("\nAscending : ");
printAsc();
printf("\nDescending : ");
printDes();
return 0;
}
hope this helps
 PeyarTheriyaa December 11, 2018Search google for "doubly linked list in c", doubly linked list is quite commonly asked question.
the one from tutorials point is good enough and quite exhaustive.
ignore functions you don't need and comments
This should be enough..
// this strcmp function returns 0 if strings are equal
int strcmp(char *s1, char *s2)
{
int l1 = strlen(s1);
int l2 = strlen(s2);
if (l1 != l2)
return l1  l2;
int i = 1;
do
{
i++;
if (s1[i] != s2[i])
return (int)s1[i]  s2[i];
} while (i < l1);
return 0;
}

PeyarTheriyaa
December 10, 2018 I would do something like this,
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5};
int[] b = {1, 1, 2, 2, 3, 3, 4, 4, 5};
int[] c = new int[a.length + b.length];
int i = 0, j = 0, end = 0;
while (i < a.length && j < b.length)
c[end++] = (a[i] <= b[j]) ? a[i++] : b[j++];
while (i < a.length)
c[end++] = a[i++];
while (j < b.length)
c[end++] = b[j++];
System.out.println(Arrays.toString(c));
}
just so that I can avoid nulls & unnecessary if conditions
while takes just as much time even when split
Yes I understand, I missed it..
But I can't seem to think of any other way..
2 loops are needed one to loop through the string the other to find the match,even if the match finding function is user defined
please, If you find an answer kindly attach a reply here
Something like this should be ok..
The program should be pretty much self explanatory
Hope this helps
static String string;
public static void main(String[] args) {
System.out.print("Enter the string : ");
string = (new Scanner(System.in)).nextLine();
for (int i = 0; i < string.length(); i++)
System.out.println("S(" + (i + 1) + "," +
string.length() + ") = " + S(i, string.length()));
for (int i = 0; i < string.length(); i++)
System.out.println("len(LCP(s(" + (i + 1) + "," +
string.length() + "),s)) = " +
LCP(S(i, string.length()), string).length());
}
static String S(int start, int end) {
return string.substring(start, end);
}
static String LCP(String a, String b) {
for (int i = a.length(); i > 0; i) {
String tmp = a.substring(0, i);
if (b.startsWith(tmp)) return tmp;
}
return "";
}

PeyarTheriyaa
December 02, 2018 a = *ptr = 32 // changing *ptr changes a and vice versa
ch = cho = 'A' (ASCII value 65) // similarly ch and cho
cho = cho+a = 'A'+32 i.e. 65+32 = 97 i.e. char 'a'
*ptr = *ptr+ch= 32+97(from previous line 'a') ie 129
so the output : 129, a

PeyarTheriyaa
December 02, 2018 This is how I'd go about it,
K will denote the level of the string in the reverse order 0 will be the last
based on the level iterate from end of the previous level to Nlevel
the rest of the string from current end to the last will be recursively solved
if the current substring is palindrome send 1 (c+1) to the next level
the c will be added to count at the end will have the no of palindromes for the current split
static Scanner sc = new Scanner(System.in);
static String input;
static int count = 0;
static int n;
public static void main(String[] args) {
System.out.print("Enter N and K : ");
n = sc.nextInt();
var k = sc.nextInt();
input = sc.nextLine();
System.out.print("Enter the String : ");
input = sc.nextLine();
checkPalin(0, 0, k);
System.out.println("The count of Palindrome in " + input + " = " + count);
}
private static void checkPalin(int c, int start, int lvl) {
if (lvl > 0)
for (int end = start + 1; end <= n  lvl; end++) {
int tmp = 0;
if (isPalin(start, end)) tmp = 1;
checkPalin(c + tmp, end, lvl  1);
}
if (lvl == 0) {
if (isPalin(start, n)) c += 1;
count += c;
}
}
private static boolean isPalin(int start, int end) {
for (int i = 0; i < (end  start) / 2; i++)
if (input.charAt(start + i) != input.charAt(end  i  1))
return false;
return true;
}

PeyarTheriyaa
November 26, 2018 This is how I'd go about it
a node having excess coins or deficit of coins requires that many moves of coins from the connected node
so the deficit or excess is to be added to the no of moves the excess or deficit is moved to or from the parent
Note: assumptions made:
only one coin can be moved per move
only up or down one step of the tree
private static Node tree;
private static int moves;
public static void main(String[] args) {
// init tree here
moves = 0;
traverse(tree);
System.out.println("The number of moves required : " + moves);
}
private static int traverse(Node tmp) {
int ret = 0;
for (Node n : tmp.kids) {
int t = traverse(n);
ret += t;
moves += Math.abs(t);
}
ret += tmp.val  1;
return ret;
}

PeyarTheriyaa
November 22, 2018 This is how I'd do it,
use counting semaphores for resources
thread will acquire required resources and process for a certain amount of time
release after the sleep
Note : variable time , t and sleep(t) have been used for fine tuning the start time of threads
and would not be required if its too much trouble
public class EgThread {
private static final Semaphore sem = new Semaphore(10);
private static final long time = System.currentTimeMillis() + 5000; // not required
public static void main(String[] args) {
MyThread[] threads = new MyThread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new MyThread(String.valueOf(i + 1));
}
for (int i = 0; i < 5; i++)
threads[i].start();
try {
for (int i = 0; i < 5; i++)
threads[i].join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
static class MyThread extends Thread {
String name;
MyThread(String name) {
this.name = name;
}
@Override
public void run() {
try {
long t = time  System.currentTimeMillis(); // not required
sleep(t); // not required
for (int i = 0; i < 10; i++) {
int req = (int) (6 * Math.random()) + 1;
System.out.println("T[" + name + "] run : " + (i + 1) + " asks for " + req + " resources");
sem.acquire(req);
System.out.println("T[" + name + "] run : " + (i + 1) + " acquires " + req + " resources");
sleep((long) (500 * Math.random()) + 200);
System.out.println("T[" + name + "] run : " + (i + 1) + " releases " + req + " resources");
sem.release(req);
}
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

PeyarTheriyaa
November 11, 2018 Hope this helps
public static void main(String[] args) {
System.out.print("Enter the limit : ");
int n = (new Scanner(System.in)).nextInt();
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i == findSOC(i)) {
list.add(i);
}
}
System.out.println(list);
}
private static int findSOC(int i) {
if (i == 0)
return 0;
return findSOC(i / 10) + cube(i % 10);
}
private static int cube(int i) {
return i * i * i;
}

PeyarTheriyaa
November 09, 2018 This is how I'd do it
1 push on (,{,[,<
2 pop on ),},],>
compare popped value
the fail conditions are
1 no opening brace
2 opening brace not matching with closing brace
3 unsatisfied opening braces
the success condition would be all braces matching in the right order
i.e stack empty at end
public class BracketChk {
static Stack<Character> stack = new Stack<>();
public static void main(String[] args) {
System.out.print("Enter the String with brackets : ");
String input = (new Scanner(System.in)).nextLine();
try {
for (int i = 0; i < input.length(); i++) {
System.out.println(stack.toString());
char c = input.charAt(i);
boolean flag = true;
switch (c) {
case '(': case '{': case '[': case '<':
stack.push(c);
break;
case ')': case '}': case ']': case '>':
char o = stack.pop(); // closing brace not having any opening brace
// throws exception
switch (c) {
case ')':
if (o != '(') flag = false;
break;
case '}':
if (o != '{') flag = false;
break;
case ']':
if (o != '[') flag = false;
break;
case '>':
if (o != '<') flag = false;
break;
}
}
if (!flag) throw new EmptyStackException(); // opening and closing brace not matching
}
if (stack.size() > 0) throw new EmptyStackException(); // more opening braces
System.out.println("Successful : Brackets balanced!!"); // all braces match
}
catch (EmptyStackException e) {
System.out.println("Unsuccessful : Brackets not balanced");
}
}
}

PeyarTheriyaa
November 08, 2018 the good thing is that only int is used so it will not take as much space as String
 PeyarTheriyaa November 08, 20181 fill an array list with the increasing numbers 1N
2 sort the array list with compare lambda expression
the comparison is to be done after converting the num to a value between 09
eg 1 10 ...19 all produce 1 only rearrange when nums produce negative
2 and 11 will be compared as 12 will produce 1 and so swapped
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
System.out.print("Enter the size : ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int i = 1; i <= n; i++) {
list.add(i);
}
// sort using num converted to 09
list.sort((o1, o2) > {
while (o1 > 9) o1 /= 10;
while (o2 > 9) o2 /= 10;
return o1  o2;
});
System.out.println("The list is : " + list.toString());
int t;
do {
System.out.print("Enter the index you want to get <negative num to exit> : ");
t = in.nextInt();
if (t >= 0 && t < n)
System.out.println("The Queried num is " + list.get(t));
else System.out.println("Error : Index out of bounds");
} while (t >= 0);
}

PeyarTheriyaa
November 08, 2018 1 keep track of the number of toffees in the boxes initially 0.
2 add the incoming toffee packet to the first box with the minimum number of toffees
note 1 : under the given circumstances this will produce the minimum max toffees in all the boxes
note 2 : I assume that you are not allowed to rearrange toffee packets in the boxes
if you need the Java program ask so in the reply
lets assume
1 rats are to be fed once and at the same time and we know how fast the poison acts, then the following would be optimal
feed rat1 with milk1 and milk2
feed rat2 with milk2 and milk3
wait for the time the poison should act
if only rat1 dies milk1 has poison
if both rat1 and rat2 die then milk2 has poison
if only rat2 dies then milk3 has poison
if no rats die then milk4 has poison
This is how I'd do it
optimizations
1: always start j after i so that we don need to check for i<j
2: i will always be less than sizemax so that there is always a array that is larger than max to check for
3: j should start after i but also i+max so that the length of a[i], a[j] in comparison will never be smaller than max
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the size of arr : ");
int size = in.nextInt();
int[] arr = new int[size];
for (int i = 0; i < size; i++) arr[i] = in.nextInt();
int max=0;
for(int i=0;i<sizemax;i++)
for(int j=i+max+1;j<size;j++)
if (arr[i]<arr[j]&&ji>max)
max=ji;
System.out.println("the max length between a[i],a[j] where a[i]<a[j] is "+max);
}

PeyarTheriyaa
October 17, 2018 Using the diff method does lower the code complexity
public class MinSumBt2 {
public static void main(String[] args) {
ArrayList<CostPair> list = new ArrayList<>();
try (Scanner in = new Scanner(new FileReader("inputMinSum"))) {
while (in.hasNext()) {
list.add(new CostPair(in.nextInt(), in.nextInt()));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
list.sort(CostPair::compareTo);
int sum = 0;
for (int i = 0; i < 100; i++)
sum += i < 50 ? list.get(i).toNY : list.get(i).toSF;
System.out.println(sum);
}
private static class CostPair implements Comparable<CostPair> {
int toNY;
int toSF;
int diff;
CostPair(int toNY, int toSF) {
this.toNY = toNY;
this.toSF = toSF;
diff = toSF  toNY;
}
@Override
public int compareTo(CostPair o) {
return diff  o.diff;
}
}
}

PeyarTheriyaa
September 24, 2018 Something like this should work
for (int i=0; i < a.length; i++)
for (int j=0; j < b.length; j++)
for (int k=0; k < b.length; k++)
for (int l=0; l < b.length; l++)
if (a[i] + b[j] == b[k] + c[l])
System.out.println(String.format("a[%d] : %d +b[%d] : %d == b[%d] : %d +c[%d] : %d",
i, a[i], j, b[j], k, b[k], l, c[l]));

PeyarTheriyaa
September 22, 2018 This is how I'd solve it
1 sort the list with the min value of the two
2 add the NY cost if NY is min or sf cost if sf is min only until either of the counts become 50
3 on any one count (NY/SF) reaches 50 add the rest of the list to the other
public class MinSumBt2 {
public static void main(String[] args) {
ArrayList<CostPair> list = new ArrayList<>();
try (Scanner in = new Scanner(new FileReader("inputMinSum"))) {
while (in.hasNext()) {
list.add(new CostPair(in.nextInt(), in.nextInt()));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
list.sort(CostPair::compareTo);
System.out.println(list);
int sum = 0;
int countNY = 0;
int countSF = 0;
for (CostPair tmp : list) {
if (countNY < 50 && countSF < 50) {
if (tmp.isNYMin) {
sum += tmp.toNY;
countNY++;
}
else {
sum += tmp.toSF;
countSF++;
}
}
else if (countNY < 50) {
sum += tmp.toNY;
countNY++;
}
else {
sum += tmp.toSF;
countSF++;
}
}
System.out.println(sum);
}
static class CostPair implements Comparable<CostPair> {
int toNY;
int toSF;
boolean isNYMin;
CostPair(int toNY, int toSF) {
this.toNY = toNY;
this.toSF = toSF;
isNYMin = toNY < toSF;
}
private int min() {
return (toNY < toSF) ? toNY : toSF;
}
private int max() {
return (toNY < toSF) ? toSF : toNY;
}
@Override
public int compareTo(CostPair c) {
if (min() == c.min())
return c.max()  max();
return min()  c.min();
}
@Override
public String toString() {
return "[" + toNY + "," + toSF + "]";
}
}
}

PeyarTheriyaa
September 22, 2018 This is how I would do it
1 list.add() adds only if duplicate not found, else increment existing
2 comparable interface on Entry class implementing compareTo()
3 sort list using the sortt command pass the compareTo of Entry to sort
4 after sorting printTopTen()
public class VideoTopTen {
public static void main(String[] args) {
// populate list using List list.add() eg.
List.add(new Entry("Mine", 1234));
List.add(new Entry("Yours", 5555));
List.add(new Entry("Mine", 1234));
List.list.sort(Entry::compareTo);
List.printTop10();
}
static class List {
static ArrayList<Entry> list;
static {
list = new ArrayList<>();
}
static void add(Entry tmp) {
boolean flag = true;
for (Entry e : list)
if (e.name.equals(tmp.name)) {
e.count += tmp.count;
flag = false;
break;
}
if (flag)
list.add(tmp);
}
static void printTop10() {
int i = 0;
for (Entry e : list) {
System.out.println(e.name + e.count);
if (i == 9) break;
i++;
}
}
}
static class Entry implements Comparable<Entry> {
String name;
int count;
Entry(String name, int count) {
this.name = name;
this.count = count;
}
@Override
public int compareTo(Entry tmp) {
return tmp.count  count;
}
}
}

PeyarTheriyaa
September 04, 2018 using a program to solve this,
Note: it also prints out the combination
public class Com1ToN
{
static int count;
public static void main(String[] args)
{
count = 0;
System.out.print("Enter N : ");
int n = (new Scanner(System.in)).nextInt();
for (int i = 0; i < n; i++)
print(1, n, i, "");
System.out.println("The count is : " + count);
}
private static void print(int s, int n, int lvl, String pre)
{
if (lvl == 0)
for (int i = s; i <= n; i++) {
System.out.println(pre + i);
count++;
}
else
for (int i = s; i <= n  lvl; i++)
print(i + 1, n, lvl  1, pre + i + " ");
}
}

PeyarTheriyaa
August 22, 2018 This is a bit too mathematical...
choosing 1 from n is nC1
choosing 2 from n is nC2
choosing 3 from n is nC3... till
choosing n from n is nCn
each combination should be added to get the total no of possible formations
nC1+nC2+...+nCn
(without going into the derivation its known that) nC0+nC1+...+nCn=2^n
nC0=1
therefore
nC1+nC2+...+nCn=(2^n)nC0
so, nC1+nC2+...+nCn=(2^n)1
This is how I'd do it,
1 get the points, populate in an ArrayList
2 call Collections.sort on the list with user defined Comparator
3 print the first n points
Note: If we don't use an ArrayList store the points in an array, manually sort the array using the Euclidean distance
simplifications done:
1 Distance from origin sqrt(x^2+y^2)
2 removal of sqrt from the equation cause squares, square roots and n considered here are always proportional under the given problem circumstances
public class NClosePoints
{
static List<Point> list;
public static void main(String[] args)
{
list = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("Enter no of points : ");
int size = in.nextInt();int i;
for (i = 0; i < size; i++) {
Point tmp = new Point(in.nextInt(), in.nextInt());
list.add(tmp);
}
System.out.print("Enter N of N closest points needed : ");
int n = in.nextInt();
Collections.sort(list, new Comparator<Point>(){
@Override
public int compare(Point p1,Point p2){
return (int) ((Math.pow(p1.x, 2)+Math.pow(p1.y, 2))(Math.pow(p2.x, 2)+Math.pow(p2.y, 2)));
}
});
i=0;
for (Point tmp : list) {
if(i<n)
System.out.println("Point "+(i+1)+" : "+tmp);
else
break;
i++;
}
}
static class Point
{
int x, y;
Point(int i, int j)
{
x = i;
y = j;
}
@Override
public String toString(){
return "( "+x+" , "+y+" )";
}
}
}

PeyarTheriyaa
August 21, 2018 This is my take on the question
case num ==0 output Zero
case num != 0
split it in 1000s (0999) append thousand, million or billion appropriately
split it in 100s (099)
case 019 append the word from n0to19
case 2099 append tens place from n10s and ones place from n0to19
split hundreds place append word from n0to19 and hundred if not empty
Note : need to append "and" if number is less than 1000 and has tens and ones place
public class Num2W
{
static String[] n0to19 = {"", " One", " Two", " Three",
" Four", " Five", " Six", " Seven",
" Eight", " Nine", " Ten", " Eleven",
" Twelve", " Thirteen", " Fourteen", " Fifteen",
" Sixteen", " Seventeen", " Eighteen", " Nineteen"};
static String[] n10s = {" Twenty", " Thirty", " Fourty", " Fifty",
" Sixty", " Seventy", " Eighty", " Ninety"};
static String[] nmulk = {"", " Thousand,", " Million,", " Billion,"};
private static String convert(int n, int sfix)
{
String inW = "";
if (n != 0) {
int tmp = n % 100;
if (tmp != 0) {
if (tmp < 20)
inW = n0to19[tmp];
else
inW = n10s[(tmp / 10)  2] + n0to19[tmp % 10];
if (sfix == 0)
inW = " and" + inW;
}
tmp = n / 100;
if (tmp != 0)
inW = n0to19[tmp] + " Hundred" + inW;
inW += nmulk[sfix];
}
return inW;
}
public static void main(String[] args)
{
int n = (new Scanner(System.in)).nextInt();
String out = "";
if (n == 0)
out = " Zero";
else
for (int i = 0; n != 0; i++) {
out = convert(n % 1000, i) + out;
n /= 1000;
}
System.out.println("In Words :" + out);
}
}

PeyarTheriyaa
August 21, 2018 Open Chat in New Window
the question isn't complete, links don't work so, type in the whole question here
 PeyarTheriyaa April 28, 2019