Incorrect conversion and display in the output - java

My code should find the smallest digit in a given number, and indicate its position. If there are several such digits, then indicate all positions.
For example,
when entering 1231
Output: position - [1 4]
The digit that is the minimum in the entered number does not need to be displayed. As it seems to me, my problem is in the output.
Help me figure out how to convert correctly, or rather display the number's position.
As I understand it, the whole problem is in the line
Integer[] s1 = getMinPos(s);
import java.util.Scanner;
import java.util.LinkedList;
public class test1 {
public static void main(String[] args) {
Scanner text = new Scanner(System.in);
System.out.println("Enter: ");
int k = text.nextInt();
String s = Integer.toString(k);
Integer[] s1 = getMinPos(s);
System.out.println("position - " + s1);
}
static Integer[] getMinPos(String num) {
LinkedList<Integer> list = new LinkedList<>();
int maxVal = -1, counter = 1;
for (char a : num.toCharArray()) {
if (maxVal < a) {
maxVal = a;
list.clear();
}
if (a == maxVal) {
list.add(counter++);
}
}
return list.toArray(new Integer[0]);
}
}

You main issue is this line:
System.out.println("position - " + s1);
You cannot print an array like that. When you try to print an array variable, it prints the object reference. Not the elements of the array. You need something like this to print it.
System.out.println("position - ");
for (int i : s1) {
System.out.print(i + " ");
}
Check how it prints the array by iterating through the elements.
When you print using this, you may find that your logic is not finding the position of the minimum value, but the position of the maximum value.
If you want to find the positions of the minimjum digit, the logic should be something like this:
static Integer[] getMinPos(String num) {
LinkedList<Integer> list = new LinkedList<>();
int minValue = '9' + 1, counter = 1;
for (char a : num.toCharArray()) {
if (a < minValue) {
minValue = a;
list.clear();
list.add(counter);
} else if (a == minValue) {
list.add(counter);
}
counter++;
}
return list.toArray(new Integer[0]);
}
Notice here that since you are comparing the char values, I have used the char value of 9 ('9') and added 1 to make sure that the starting minValue is always higher than any digit.
Then, there's another issue where you do not add the first index to your list. I've fixed that too.
You also do not increase the counter when you find a value greater than a. (Or in the fixed version, when the value of a is greater than minValue. That will be causing a bug, where your program will return incorrect indexes. So, the incrementing the counter is moved out from the if-else blocks.

Related

Java program to find the duplicate values of an array of integer using simple loop

public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
for(int i= 0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if((array[i])==(array[j]) && (i != j)){
System.out.println("element occuring twice are:" + array[j]);
}
}
}
}
}
this program work fine but when i compile it, it print the values again and again i want to print the duplicate value once for example if 9 is present 5 times in array so it print 9 once and if 5 is present 6 times or more it simply print 5...and so on....this what i want to be done. but this program not behave like that so what am i missing here.
your help would be highly appreciated.
regards!
Sort the array so you can get all the like values together.
public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
Arrays.sort(array);
for (int a = 0; a < array.length-1; a++) {
boolean duplicate = false;
while (array[a+1] == array[a]) {
a++;
duplicate = true;
}
if (duplicate) System.out.println("Duplicate is " + array[a]);
}
}
}
The problem statement is not clear, but lets assume you can't sort (otherwise the problem greatly simplifies). Lets also assume the space complexity is constrained, and you can't keep a Map, etc, for counting the frequency.
You can use use lookbehind, but this unnecessarily increases the time complexity.
I think a reasonable approach is to reserve the value -1 to indicate that an array position has been processed. As you process the array, you update each active value with -1. For example, if the first element is 32, then you scan the array for any value 32, and replace with -1. The time complexity does not exceed O(n^2).
This leaves the awkcase case where -1 is an actual value. It would be required to do a O(n) scan for -1 prior to the main code.
If the array must be preserved, then clone it prior to processing. The O(n^2) loop is:
for (int i = 0; i < array.length - 1; i++) {
boolean multiple = false;
for (int j = i + 1; j < array.length && array[i] != -1; j++) {
if (array[i] == array[j]) {
multiple = true;
array[j] = -1;
}
}
if (multiple)
System.out.println("element occuring multiple times is:" + array[i]);
}
What you can do, is use a data structure that only contains unique values, Set. In this case we use a HashSet to store all the duplicates. Then you check if the Set contains your value at index i, if it does not then we loop through the array to try and find a duplicate. If the Set contains that number already, we know it's been found before and we skip the second for loop.
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
HashSet<Integer> duplicates = new HashSet<>();
for(int i= 0;i<array.length-1;i++)
{
if(!duplicates.contains(array[i]))
for(int j=i+1;j<array.length;j++)
{
if((array[i])==(array[j]) && (i != j)){
duplicates.add(array[i]);
break;
}
}
}
System.out.println(duplicates.toString());
Outputs
[3, 4, 5, 6, 7, 88, 8, 9]
I recommend using a Map to determine whether a value has been duplicated.
Values that have occurred more than once would be considered as duplicates.
P.S. For duplicates, using a set abstract data type would be ideal (HashSet would be the implementation of the ADT), since lookup times are O(1) since it uses a hashing algorithm to map values to array indexes. I am using a map here, since we already have a solution using a set. In essence, apart from the data structure used, the logic is almost identical.
For more information on the map data structure, click here.
Instead of writing nested loops, you can just write two for loops, resulting in a solution with linear time complexity.
public void printDuplicates(int[] array) {
Map<Integer, Integer> numberMap = new HashMap<>();
// Loop through array and mark occurring items
for (int i : array) {
// If key exists, it is a duplicate
if (numberMap.containsKey(i)) {
numberMap.put(i, numberMap.get(i) + 1);
} else {
numberMap.put(i, 1);
}
}
for (Integer key : numberMap.keySet()) {
// anything with more than one occurrence is a duplicate
if (numberMap.get(key) > 1) {
System.out.println(key + " is a reoccurring number that occurs " + numberMap.get(key) + " times");
}
}
}
Assuming that the code is added to ArrayTest class, you could all it like this.
public class ArrayTest {
public static void main(String[] args) {
int array[] = {32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
ArrayTest test = new ArrayTest();
test.printDuplicates(array);
}
}
If you want to change the code above to look for numbers that reoccur exactly twice (not more than once), you can change the following code
if (numberMap.get(key) > 1) to if (numberMap.get(key) == 2)
Note: this solution takes O(n) memory, so if memory is an issue, Ian's solution above would be the right approach (using a nested loop).
// print duplicates
StringBuilder sb = new StringBuilder();
int[] arr = {1, 2, 3, 4, 5, 6, 7, 2, 3, 4};
int l = arr.length;
for (int i = 0; i < l; i++)
{
for (int j = i + 1; j < l; j++)
{
if (arr[i] == arr[j])
{
sb.append(arr[i] + " ");
}
}
}
System.out.println(sb);
Sort the array. Look at the one ahead to see if it is duplicate. Also look at one behind to see if this was already counted as duplicate (except when i == 0, do not look back).
import java.util.Arrays;
public class ArrayTest{
public static void main(String[] args) {
int array[] = {32,32,3,3,4,5,6,88,98,9,9,9,9,9,9,1,2,3,4,5,6,4,3,7,7,8,8,88,88};
Arrays.sort(array);
for(int i= 0;i<array.length-1;i++){
if((array[i])==(array[i+1]) && (i == 0 || (array[i]) != (array[i-1]))){
System.out.println("element occuring twice are:" + array[i]);
}
}
}
}
prints:
element occuring twice are:3
element occuring twice are:4
element occuring twice are:5
element occuring twice are:6
element occuring twice are:7
element occuring twice are:8
element occuring twice are:9
element occuring twice are:32
element occuring twice are:88

Print sum of unique values of an integer array in Java

I am yet again stuck at the answer. This program prints the unique values but I am unable to get the sum of those unique values right. Any help is appreciated
public static void main(String args[]){
int sum = 0;
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
Set<Integer> setUniqueNumbers = new LinkedHashSet<Integer>();
for (int x : numbers) {
setUniqueNumbers.add(x);
}
for (Integer x : setUniqueNumbers) {
System.out.println(x);
for (int i=0; i<=x; i++){
sum += i;
}
}
System.out.println(sum);
}
This is a great example for making use of the Java 8 language additions:
int sum = Arrays.stream(numbers).distinct().collect(Collectors.summingInt(Integer::intValue));
This line would replace everything in your code starting at the Set declaration until the last line before the System.out.println.
There's no need for this loop
for (int i=0; i<=x; i++){
sum += i;
}
Because you're adding i rather than the actual integers in the set. What's happening here is that you're adding all the numbers from 0 to x to sum. So for 23, you're not increasing sum by 23, instead, you're adding 1+2+3+4+5+....+23 to sum. All you need to do is add x, so the above loop can be omitted and replaced with a simple line of adding x to sum,
sum += x;
This kind of error always occures if one pokes around in low level loops etc.
Best is, to get rid of low level code and use Java 8 APIs:
Integer[] numbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sum = Arrays.stream(numbers)
.distinct()
.mapToInt(Integer::intValue)
.sum();
In this way there is barely any space for mistakes.
If you have an int array, the code is even shorter:
int[] intnumbers = {1,2,23,43,23,56,7,9,11,12,12,67,54,23,56,54,43,2,1,19};
int sumofints = Arrays.stream(intnumbers)
.distinct()
.sum();
So this is my first time commenting anywhere and I just really wanted to share my way of printing out only the unique values in an array without the need of any utilities.
//The following program seeks to process an array to remove all duplicate integers.
//The method prints the array before and after removing any duplicates
public class NoDups
{
//we use a void static void method as I wanted to print out the array without any duplicates. Doing it like this negates the need for any additional code after calling the method
static void printNoDups(int array[])
{ //Below prints out the array before any processing takes place
System.out.println("The array before any processing took place is: ");
System.out.print("{");
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i]);
if (i != array.length - 1)
System.out.print(", ");
}
System.out.print("}");
System.out.println("");
//the if and if else statements below checks if the array contains more than 1 value as there can be no duplicates if this is the case
if (array.length==0)
System.out.println("That array has a length of 0.");
else if (array.length==1)
System.out.println("That array only has one value: " + array[0]);
else //This is where the fun begins
{
System.out.println("Processed Array is: ");
System.out.print( "{" + array[0]);//we print out the first value as it will always be printed (no duplicates has occured before it)
for (int i = 1; i < array.length; i++) //This parent for loop increments once the all the checks below are run
{
int check = 0;//this variable tracks the amount of times an value has appeared
for(int h = 0; h < i; h++) //This loop checks the current value for array[i] against all values before it
{
if (array[i] == array[h])
{
++check; //if any values match during this loop, the check value increments
}
}
if (check != 1) //only duplicates can result in a check value other than 1
{
System.out.print(", " + array[i]);
}
}
}
System.out.print("}"); //formatting
System.out.println("");
}
public static void main(String[] args)
{ //I really wanted to be able to request an input from the user but so that they could just copy and paste the whole array in as an input.
//I'm sure this can be done by splitting the input on "," or " " and then using a for loop to add them to the array but I dont want to spend too much time on this as there are still many tasks to get through!
//Will come back and revisit to add this if I remember.
int inpArray[] = {20,100,10,80,70,1,0,-1,2,10,15,300,7,6,2,18,19,21,9,0}; //This is just a test array
printNoDups(inpArray);
}
}
the bug is on the line
sum += i;
it should be
sum += x;

Finding the largest number in an array of integers

I am trying to recursively find the largest element in an array. The user has to input the number of elements that the array will have. My error is that if that the list does not have an element which is larger than the number of elements in the list, the output of the largest number will be the number of elements in the list. eg: array of 5 integers containing {1 1 1 2 3}. the answer will be 5 and not 3.
import java.util.*;
public class test7 {
public static int findLargest(int[] a, int max) {
int i=0, j=0, tempmax=0;
if (a.length == 1) return a[0]>max ? a[0]:max;
else if(max < a[i]){
max = a[i];
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
else{
int[] tempArr = new int[a.length -1];
for (i=1; i<a.length; i++){
tempArr[j] = a[i];
j++;
}
tempmax = findLargest(tempArr, max);
return tempmax;
}
}
public static void main(String[] args) {
int[] values = new int[100];
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of elements in your list: ");
int x = scan.nextInt();
if(x>1 || x<100){
for (int i=0; i<=(x-1); i++){
System.out.print("Enter your number: ");
System.out.println();
values[i] = scan.nextInt();
}
System.out.println();
System.out.println("The largest number is: "+findLargest(values, x));
}
else System.out.println("The maximum number of elements must be less than 100");
}
}
You call your method with:
System.out.println("The largest number is: "+findLargest(values, x))
This tells it to assume the largest number is x and try to find anything in the list that is greater than that. Of course, this produces the exact problem you described.
In general, when finding a maximum number, you want to initialize your candidate to the lowest number possible, or to the first number in your array.
If you initialize to the lowest number possible (Integer.MIN_VALUE) then as soon as you start your algorithm, the first number will definitely be bigger than it and will be chosen as the next candidate for maximum.
If you initialize to the first item in your array, then if that number is the highest, all well and good. If it is not, then when you encounter the next higher number, it will become the candidate, and all is good.
Which one you choose is up to you (and depends also on whether an empty array is possible), but the thing to remember is never to select an initial candidate that might be greater than all the elements in the array.
Try this working example:
public static void main(String[] args)
{
int[] numbers = {2, 5134, 333, 123, 8466};
int largest = numbers[0];
for(int i = 1;i<numbers.length;i++)
{
largest = Math.max(largest, numbers[i]);
}
System.out.println("Largest number: "+largest);
}
As a method that would look like this:
public static int max(int first, int... more)
{
for(int element:more)
{
first = Math.max(first, element);
}
return first;
}
You can then call it using something like max(1,23,564,234,543);

Trying to display the ints in an array that only occur once

I have an array I have created that is a length of 25 and and has randomly generated numbers in it 1 to 25. The array will pretty much always have duplicate numbers in it and all i want to do is display the numbers that occur only once in the array. The code I have so far seems to work as long as the numbers that are repeated only repeat an even number of times. My question is how do I make this work so I only get numbers that occur once added to my string.
I can not use hash or set or anything like that this is part of an assignment.
int count2 = 0;
for (int d = 0; d < copy.length-1; d++)
{
int num = copy[d];
if (num != copy[d+1])
{
s = s + "," + num;
}
else
{
d++;
}
}
Use a HashSet!
Construct two new HashSets, one for the elements appearing just once and one for the duplicates
Iterate through your array
For each value in the array check if it's already in the set of duplicates. If so, do nothing else and continue to the next iteration
Check if the value is already in the set of elements appearing just once
If it's not, add it. If it is, remove it and add it to a list of duplicates
Call hashSet.toArray() and then you will have an array of all the elements appearing only once
You can convert the array to a string or use it however you wish
This approach is very efficient as search, insert, and remove are all O(1) in a HashSet.
I would start by writing a separate method to count the number of occurrences of a value in the given array so you can count how many occurrences there are for each value using a For-Each Loop like
private static int count(int[] arr, int value) {
int count = 0;
for (int item : arr) {
if (item == value) {
count++;
}
}
return count;
}
Then you can leverage that like
public static String toUniqueString(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int value : arr) {
if (count(arr, value) == 1) {
if (sb.length() != 0) {
sb.append(", ");
}
sb.append(value);
}
}
return sb.toString();
}
Finally, to test it
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[25];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(arr.length) + 1;
}
System.out.println(toUniqueString(arr));
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException in Finding Max Element

Whenever I am trying to run this code, it gives me out of bound exception. Can anyone point me out what's wrong with it.
package com.programs.interview;
import java.util.Scanner;
public class FindMaxNumInArray {
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
System.out.print("Enter the size of the array: ");
int arraySize = scan.nextInt();
int[] myArray = new int[arraySize];
System.out.print("Enter the " + arraySize + " values of the array: ");
for (int i = 0; i < arraySize; i++)
myArray[i] = scan.nextInt();
for (int j = 0; j < arraySize; j++)
System.out.println(myArray[j]);
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
}
public static int maximum(int[] arr, int Arraylength){
int tmp;
if (Arraylength == 0)
return arr[Arraylength];
tmp = maximum(arr, Arraylength -1);
if (arr[Arraylength] > tmp)
return arr[Arraylength];
return tmp;
}
}
Output
Enter the size of the array: 5 Enter the 5 values of the array: 1 2 3
4 5 1 2 3 4 5 Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
com.programs.interview.FindMaxNumInArray.maximum(FindMaxNumInArray.java:26)
at
com.programs.interview.FindMaxNumInArray.main(FindMaxNumInArray.java:17)
This is the problem:
if (arr[Arraylength] > tmp)
Valid array indexes go from 0 to length-1 inclusive. array[array.length] is always invalid, and on the initial call, ArrayLength is equal to arr.length.
It's not clear why you're using recursion at all, to be honest. An iterative solution would be much simpler - but you'll need to work out what you want to do if the array is empty.
EDIT: If you really want how I would write the recursive form, it would be something like this:
/** Returns the maximum value in the array. */
private static int maximum(int[] array) {
if (array.length == 0) {
// You need to decide what to do here... throw an exception,
// return some constant, whatever.
}
// Okay, so the length will definitely be at least 1...
return maximumRecursive(array, array.length);
}
/** Returns the maximum value in array in the range [0, upperBoundExclusive) */
private static int maximumRecursive(int[] array, int upperBoundExclusive) {
// We know that upperBoundExclusive cannot be lower than 1, due to the
// way that this is called. You could add a precondition if you really
// wanted.
if (upperBoundExclusive == 1) {
return array[0];
}
int earlierMax = maximumRecursive(array, upperBoundExclusive - 1);
int topValue = array[upperBoundExclusive - 1];
return Math.max(topValue, earlierMax);
// Or if you don't want to use Math.max
// return earlierMax > topValue ? earlierMax : topValue;
}
you can't access
arr[Arraylength]
the last element would be at
arr[Arraylength -1]
for example if you have
int arr[] = new int[5];
then the elements would be at 4, because index starts from 0
arr[0], arr[1], arr[2], arr[3], arr[4]
Your issue is in the following piece of code:
if (arr[Arraylength] > tmp)
return arr[Arraylength];
Indexes start at 0, so you will be out of bound for an array with 5 elements [1,2,3,4,5] indexes: [0,1,2,3,4].
I would use a plain loop. Java doesn't do recursion particularly well.
public static int maximum(int[] arr) {
int max = Integer.MIN_VALUE;
for(int i : arr) if (i > max) max = i;
return max;
}
here
System.out.println("In the array entered, the larget value is "+ maximum(myArray,arraySize) + ".");
you are passing the arraysize where in maximum method you are returning arr[Arraylength] which giving ArrayIndexOutOfBound so change either in calling maximum(yArray,arraySize-1) or return arr[Arraylength-1] statement.

Categories

Resources