Find minimum pair of numbers whose sum is 15 - java

I am trying to find the minimum pair of numbers to achieve sum of 15. I am creating new array for them and passing that array to method which is adding element of that array and generating true or false. array size will increase if method returns false.
public class FindMinimum {
static int arr[] = { 10, 3, 2, 13 };
static int numArr[] = new int[30];
static int arrLength = 2;
static boolean status = false;
static int number;
public static void main(String args[]) {
for (int i = 0; i < arrLength; i++) {
numArr[i] = arr[i];
}
if (checkPair(numArr)) {
System.out.println("Number found");
} else {
arrLength = arrLength + 1;
System.out.println("Increasing array length by one");
}
}
public static boolean checkPair(int x[]) {
for (int i = 0; i < x.length; i++) {
number = number + x[i];
}
if (number == 15) {
status = true;
for (int i : x) {
System.out.println(i);
}
} else {
status = false;
}
return status;
}
}
Expected result is minimum pair of addition that is "13 ,2"

If I understand correctly need to find minimum pair which always add to 15. If this is correct below code should solve it.
public static void main(String args[]) {
Arrays.sort(arr);
for (int i=0,j=arr.length-1;i<arr.length && j>=0;) {
if ((arr[i]+arr[j])<15) {
/*System.out.println(arr[i]+"-"+arr[last-i]);
break;*/
i++;
} else if ((arr[i]+arr[j])>15) {
j--;
} else {
System.out.println(arr[i]+"-"+arr[j]);
break;
}
}
}

import java.util.Scanner;
public class FindMinimumPair {
static Scanner sc = new Scanner(System.in);
static int userArr[];
static int numArr[]; // New array to take number / pairs from main array to compare with else numbers
// in the main array
static int arrLength = 1; // increase the array length of numArr if pair is more than 2 numbers
static boolean status = false; // check method returns true or false
static int sum;
public static void main(String args[]) {
System.out.println("Sum of pair should be ?");
sum = sc.nextInt();
System.out.println("Enter the lenght of an array");
int userArrLength = sc.nextInt();
userArr = new int[userArrLength];
System.out.println("Enter array integers upto " + userArrLength);
for (int i = 0; i < userArrLength; i++) {
userArr[i] = sc.nextInt();
}
// Loop to read numbers from main array
for (int i = 0; i < userArr.length; i++) {
// Defines the length of new array
numArr = new int[arrLength]; // initialize the new array
// Loop to add numbers into new array
for (int j = 0; j < arrLength; j++) {
numArr[j] = userArr[j]; // add numbers into new array
}
if (check(numArr)) { // call check method and pass new array in it
for (int a : numArr) { // if returns true then print that array (contains the pair)
System.out.print(a + " ");
}
System.out.print(userArr[numArr.length]); // print the last number which is the part of numArr
System.out.println(" is equals to " + sum);
} else {
System.out.println("Numbers not found");
}
arrLength = arrLength + 1; // increase the array length if false
}
}
public static boolean check(int number[]) {
int x = 0;
// Loop to make sum of all numbers of numArr (make it single number)
for (int j = 0; j < number.length; j++) {
x = x + number[j];
}
outer: for (int i = 0; i < number.length; i++) { // loop for elements in numArr array
for (int j = 0; j < userArr.length; j++) { // loop for given array elements
if (x + userArr[j] == sum) { // check each number of given array with the sum of numArr
status = true;
break outer; // breaks outer loop and returns true
} else {
status = false;
}
}
}
return status;
}
}

Related

randomly generate 100 unique numbers using Math.random [duplicate]

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

Core Java Practical Questions

A Test array has the following property:
a[0] = a[1] + a[2] = a[3] + a[4] + a[5] = a[6] + a[7] + a[8] + a[9] = ...
The length of a Test array must be n*(n+1)/2 for some n.
Write a method named isTestArray that returns 1 if its array argument is a Test array, otherwise it returns 0. The function signature is:
int isMadhavArray(int[ ] a)
Example:
This is what I have tried:
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a){
boolean isEq=true;
for(int i=0;i<a.length;i++){
int n=i, value=a.length;
int equation=n*(n+1)/2;
if(value==equation)
{
for(int x=0,y=1;y<a.length;x++,y++){
if(a[0]==a[x]+a[y]){
//having problem over here :(
}
}
}
else
isEq=false;
}
if(isEq)
return 1;
else
return 0;
}
}
Number of elements in sum increases by 1 in every portion.
You should do 2 things:
Write a method that will calculate sum of N elements starting from K position in array
Increment i with the number of the smallest portion in iteration
example code:
int portionSize = 1; // number of elements to sum
int position = 0; // index of first element
while (position + 2 * portionSize + 1 < array.length) { // condition for last iteration
if (sum(position, portionSize) != sum(position + portionSize, portionSize + 1) {
return false; // if not equal, return immediately
}
position += portionSize;
portionSize++;
}
Here is my attempt for your troubling inner for loop. Because each time you loop, you increment the number of indexes you need to add by one, so I think you need another nested loop like this. I know it is ugly. Can't blame me, I am a beginner.
public class TestArray {
public static void main(String[] args) {
System.out.println(isTestArray(new int[] {2,1,1,4,-1,-1}));
}
static int isTestArray(int[] a) {
boolean isEq = false;
for(int i=0; i < a.length; i++) {
int n=i, value = a.length;
int equation= n*(n+1)/2;
if (value==equation) {
int index = 1;
for (int x = 1; x < a.length; x++) {
int total = 0;
for (int y = index, count = 0; count < x+1; y++, count++) {
if (y!= a.length) {
total += a[y];
if (total == a[0])
isEq = true;
else
isEq = false;
index++;
}
else
break;
}
}
}
}
if (isEq)
return 1;
else
return 0;
}
public class TestArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(isTestArray(new int[] {2,1,1}));
System.out.println(isTestArray(new int[] {3, 1, 2, 3, 0}));
}
static int isTestArray(int[] a){
boolean isEq=false, isEx=false;
int equation=0,value=a.length;
//for equation check
for(int n=0;n<value;n++){
equation=n*(n+1)/2;
if(value==equation){
isEx=true;
break;
}
}
//if equation is true
if(isEx)
{
int x=1,y=3,c=0,sum=0;
do{
for(int I=x,J=y;I<J;I++){
sum=sum+a[I];
}
if(a[0]==sum){
isEq=true;
sum=0;
}
else{
isEq=false;
break;
}
c++;
x=y;
y=x+2+c;
}while(x<a.length);
}
//last operation of return
if(isEq)
return 1;
else
return 0;
}
}
import java.io.*;
public class StackQues1{
static boolean flag = true;
static int arrLength = 0;
public static void main(String args[]){
Console c = System.console();
System.out.println("Enter the length of array - ");
arrLength = Integer.parseInt(c.readLine());
//Let max val of n<=20
//To check n(n+1)/2
boolean nFlag = false;
for(int n=1;n<=20;n++){
if(arrLength == (n*(n+1))/2){
nFlag = true;
}
}
if(!nFlag){
System.out.println("Length of array is not in the form of (n*(n+1))/2");
}else{
int arr[] = new int[arrLength];
System.out.println("Enter the elements of array - ");
for(int i=0;i<arr.length;i++){
arr[i] = Integer.parseInt(c.readLine());
}
System.out.println("Returned value = "+isTestArray(arr));
}
}
//Logic Implementation
public static int isTestArray(int[] arr){
int sum = 0;
int noOfElements=0;
for(int i=0;i<arr.length;){
noOfElements++;
sum=0;
for(int j=1;j<=noOfElements;j++){
sum=sum+arr[i];
i++;
}
if(arr[0] == sum){
flag = true;
}else{
flag = false;
break;
}
}
if(flag){
return 1;
}else{
return 0;
}
}
}

Java - (Print distinct numbers)

I'm trying to solve this problem:
"Write a program that reads in ten numbers and displays the number of distinct numbers and the distinct numbers separated by exactly one space."
My code at the moment does not save all distinct numbers and at time repeatedly display 0. If anyone can see where my logic has gone wrong, any tip will be helpful. Thank you!
public class PracticeProject
{
public static void main(String args[])
{
int[] number = new int[10];
int[] counter = new int[10];
int numcounter = 0;
numGen(number);
numcounter = distNum(number, counter, numcounter);
dispDist(counter, numcounter);
}
public static void numGen(int[] number)
{
Random rand = new Random();
for (int i = 0; i < number.length; i++)
{
number[i] = rand.nextInt(10);
System.out.print(number[i] + " ");
}
System.out.println();
}
public static int distNum(int[] number, int[] counter, int numcounter)
{
for (int i = 0; i < number.length; i++)
{
for (int j = 0; j <= i; j++)
{
if (counter[j] == number[i])
{
break;
}
if (j == i)
{
counter[j] = number[i];
numcounter++;
}
}
}
return numcounter;
}
public static void dispDist(int[] counter, int numcounter)
{
for (int i = 0; i < numcounter; i++)
{
System.out.print(counter[i] + " ");
}
}
}
The problem is with the logic in your distNum() method, which was not correctly removing all duplicates from the output array. Try using this version instead:
public static int distNum(int[] number, int[] counter, int numcounter) {
for (int i = 0; i < number.length; i++) {
boolean isUnique = true;
for (int j = 0; j < numcounter; j++) {
if (counter[j] == number[i]) {
isUnique = false;
break;
}
}
if (isUnique) {
counter[numcounter] = number[i];
numcounter++;
}
}
return numcounter;
}
I walk through the array of random numbers, and for each one I scan counter to see if the value has already been encountered. If it be a duplicate, then it does not get added to the unique list.
This method was tested along with the rest of your original code using IntelliJ, and it appears to be working correctly.
If you use array to store your counters, you need to set default value, otherwise if your array have multiple 0, it distinguish by equaling. because the int array default values is 0.
and you can use list or vector to store your counters.
public static void main(String args[]) {
int[] number = new int[10];
int[] counter = new int[10];
List<Integer> counters = new ArrayList<Integer>();
int numcounter = 0;
numGen(number);
numcounter = distNum(number, counters, numcounter);
dispDist(counters, numcounter);
}
public static void numGen(int[] number) {
Random rand = new Random();
for (int i = 0; i < number.length; i++) {
number[i] = rand.nextInt(10);
System.out.print(number[i] + " ");
}
System.out.println();
}
public static int distNum(int[] number, List<Integer> counters, int numcounter) {
for (int i : number) {
if (!counters.contains(i)){
counters.add(i);
}
}
return numcounter;
}
public static void dispDist(List<Integer> counter, int numcounter) {
for (Integer i : counter) {
System.out.print(i + " ");
}
}
Try put below function .... using Hashmap... Key will be no. and value will be the disctinct time it occured.
public void duplicate(int[] a) {
HashMap<Integer, Integer> h = new HashMap<Integer, Integer>();
for (int i = 0; i < a.length; i++) {
Integer j = (int) h.put(a[i], 1);
if (j != null) { // checking if already in hashmap
h.put(a[i], j + 1); // if there then incrementing value
}
}
Iterator it = h.entrySet().iterator(); // displaying value you can have you logic here
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

How do I call my methods to my main method?

Basically I need to call my "sum" and "sumOfEvens" methods into the main method. The "sum" method is for when the array contains the lucky numbers as seen in the "isLucky" method. The "sumOfEvens" method adds of the even numbers if the array doesn't contain a lucky number.
So "sum" = true
and "sumOfEvens" = false
So here is my code...
import java.util.Scanner;
public class FunArrays {
public static void main(String[] args) {
luckyNumber1 = 7;
luckyNumber2 = 13;
luckyNumber3 = 18;
int[] a=new int[10];
Scanner sc=new Scanner(System.in);
System.out.println("Please enter numbers...");
for(int j = 0; j < a.length; j++)
a[j] = sc.nextInt();
}
public static int sum(int [ ] value)
{
int i, total = 0;
for(i=0; i<10; i++)
{
total = total + value[ i ];
}
return (total);
}
static int sumOfEvens(int array[])
{
int sum = 0;
for(int i = 0; i < array.length; i++>) {
if(array[i] % 2 == 0)
sum += array[i];
}
return sum;
}
public static boolean isLucky (int[] array)
{
if ( array[i] == 7 || array[i] == 13 || array[i] == 18 )
return true;
else
return false
}
// write the static methods isLucky, sum, and sumOfEvens
}
boolean b = isLucky(a);
int result;
if(b)
result = sum(a);
else
result = sumOfEvens(a);
You can do it in one line:
int result = isLucky(a) ? sum(a) : sumOfEvens(a);

Categories