How to sort array of numbers without gaps? - java

I have numbers like: 1,7,1,5 and I want to sort them without gaps between them (i.e.) 1,7,1,5 gets sorted to 1,1,2,3. (5 turns into 2; 7 turns into 3).
My code looks like this (works fine), but in some cases returns null pointer ex, or something like that :/
public void shake(Car[] c){
for(int i = 1; i < MaxPriority; i++)
if(!isCarWithPriority(i, c))
for(int j = i; j < 10; j++)
if(isCarWithPriority(j, c))
for(int k = 0; k < getCarsWithPriority(j, c).length; k++)
getCarsWithPriority(j, c)[k].setPriority(i);
}
Can you help me?

You can try iterating through the numbers after sorting them. subtract 1st from 2nd if result is 0 then dont do anything else replace 2nd by first + 1 then compare 3rd one in the same way with second.. keep on till last number. you will get the desired output. This can be achieved by a single loop in java.

This will do the trick
public static void main(String[] a) {
Integer [] arr = {1,7,1,5};
Arrays.sort(arr);
for (Integer integer : arr) {
System.out.println(integer);
}
for(int i=0; i< arr.length-1 ;i++){
if(arr[i+1]-arr[i] ==0){
continue;
}else{
arr[i+1] =arr[i]+1;
}
}
System.out.println("--------------------");
for (Integer integer : arr) {
System.out.println(integer);
}
}

Related

String-Word counter

I have to print the count of the words in a string which are repeated exactly N times?
example:
one two three four three two five
1
output:3
since one,four and five appears only once.
My code shows me the output as 1.
what is wrong with my code and logic?thank you.
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
String s=scan.nextLine(),b;
int n=scan.nextInt();
int c=0,f=0,i;
String[] a=s.split(" ");
for(i=0;i<a.length;i++)
{
b=a[i];
for(int j=i+1;j<a.length;j++)
{
if(b.equalsIgnoreCase(a[j]))
{
c++;
}
}
if(n==c)
{
f++;
}
else
{
c=0;
}
}
System.out.print(f);
}
}
I see three reasons that makes your result incorrect.
First one is c
If a word is here once only, then the if statement if(b.equalsIgnoreCase(a[j])) will never be true. Which means that c will be always equal to 0.
So you you need to use 1 as default value for c or you should check the value of c using the following statement if (n == c + 1)
The second point is that you should reset the value of c even if it is equal to n.
Then with this double for loop:
for (i = 0; i < a.length; i++) {
b = a[i];
for (int j = i + 1; j < a.length; j++) {
When you searching for a value that is there once only, the last occurence of every words will be counted as well.
There is lot of ways to solve that. one of them is to use a Set<String> and only count for the words that has not been used before.
So at the end you will have something similar to that:
int c=1,f=0,i;
String[] a=s.split(" ");
Set<String> words = new HashSet<>();
for (i = 0; i < a.length; i++) {
b = a[i];
if (words.add(b)) {
for (int j = i + 1; j < a.length; j++) {
if (b.equalsIgnoreCase(a[j])) {
c++;
}
}
if (n == c) {
f++;
}
c = 1;
}
}
I think It's because you don't initialize C when n==c . Therefor it increases to 1 after one and one are matched. And it's not working well . It should be 0 for every loop
Also why j starts from i+1? After each loop it will lose comparison one by one Since a[j] is getting smaller. It should always containt list of full input numbers

Java - iterate through ArrayList for only increasing elements

Here is my ArrayList:
[1,2,1,0,3,4]
I'm trying to return this:
[1,2,3,4]
Here is my current attempt:
for (int i = 0; i < myArray.size() - 1; i++) {
if (myArray.get(i) < myArray.get(i + 1)) {
System.out.println("Increasing sequence...");
}
}
However, this is not returning the desired output, any ideas?
You'll have to maintain an index (or value) of the last element that you had printed and store it in some variable. Then, you'll have to use the stored element for every new element and check if is greater than the stored element.
As you have mentioned, the first element has to be anyway printed, no matter what.
Something like this might work:
List<Integer> myArray = Arrays.asList(new Integer[]{1,2,1,0,3,4});
System.out.println(myArray.get(0));
int prevPrint = myArray.get(0);
for (int i = 1; i < myArray.size();i++) {
if (myArray.get(i) > prevPrint) {
System.out.println(myArray.get(i));
prevPrint = myArray.get(i);
}
}
The reason why your program was failing was because you were comparing the adjacent two values only and it was possible that you might have already printed a value which is greater than any of the two adjacent values.
A similar question, but a totally different approach (LIS) exists and can be found here
A slight variant on Parijat's answer to avoid repeating the System.out.println:
for (int j = 0; j < myArray.size();) {
System.out.println(myArray.get(j));
int start = j;
do {
++j;
while (j < myArray.size() && myArray.get(j) <= myArray.get(start));
}
Try this,
public static List<Integer> findIncreasingOrder(int[] nums) {
List<Integer> result = new ArrayList<>();
int MAX = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
int value = nums[i];
if (value >MAX){
System.out.println(value);
MAX = value;
result.add(value);
}
}
return result;
}

I want to find the 10 first Amicable Pair with only use of arrays, loops and conditions but I'm very new to java and programming in general

I think I know how to enter the sum of division into cell on the array but stuck on how to compare between the arrays and print the 10 pairs.
My code so far:
public static void main(String[] args) {
int sum1=0,sum2=0;
int[] arr1=new int[67000];
int[] arr2=new int[67000];
for(int i =0;i<=10;i++){
for(int j =1;j<arr1.length;j++){
for(int k =0;k<j;k++){
if(j%k==0){
sum1+=k;
}
}arr1[j]=sum1;
}
for(int j =1;j<arr2.length;j++){
for(int k =0;k<j;k++){
if(j%k==0){
sum2+=k;
}
}arr2[j]=sum2;
}
}
}
You are calculating the same values in both the arrays. Just create the array once.
for (int j = 2; j < arr.length; j++) {
int sum = 0;
for (int k = 1; k < j; k++) {
if (j % k == 0) {
sum += k;
}
}
arr[j] = sum;
}
Now, here, arr[n] is the sum of the proper divisors of a number n.
We can compare the pairs by looping through arr as:
int cnt = 0, first = 2;
while(cnt < 10) {
int second = arr[first];
if (second >= arr.length) {
continue;
}
if (second > first) {
if (first == arr[second]) {
System.out.printf("%d %d\n", first, second);
cnt++;
}
}
first++;
if (first >= arr.length) {
break;
}
}
The first check is to avoid overrunning the array index, the second > first check is to make sure we only look forward and not rediscover a pair twice.
And then the main check is first == arr[second] which is what amicable numbers are. What it's saying is that if the sum of divisors of the second number which in fact is the sum of divisors of the first number is the first number itself, then the numbers are amicable pairs.
Side Note:
The program could probably be written in other better ways.
For example when finding the sum, looping up to the square root of the number in question is enough as the divisors mirror each other.

Find "Missing" Integer in a Java Array

Given an array A[] of length n, find a "missing" number k such that:
k is not in A
0<=k<=n
I've seen similar questions asked where the A[] contains numbers 1 to n with one number missing, but in this question, A[] can contain any numbers. I need a solution in O(n) time. For example,
A = {1,2,3} -> 0
A = {0,1,2} -> 3
A = {2,7,4,1,6,0,5,-3} -> 3,8
I've gotten as far as checking if 0 or n are in the array, and if not, return 0 or n, but I cannot seem to think of any other solution. This problem seems considerably more difficult given the fact that A can contain any numbers and not necessarily numbers 1 to n or something like that.
Linearly iterate over the array and "cross out" every number you encounter. Then iterate of that listed of crossed out numbers again and see which one is missing.
public static int getMissingNumber(int[] A)
{
int n = A.length;
boolean[] numbersUsed = new boolean[n + 1]; //Because the definition says 0 <= k <= n, so k = n is also possible.
for(int k = 0; k < n; k++)
{
if(A[k] <= n && A[k] >= 0) //No negative numbers!
numbersUsed[A[k]] = true;
}
for(int k = 0; k <= n; k++)
{
if(numbersUsed[k] == false)
return k;
}
return -1; //nothing found
}
Complexity is 2*n because of the two for loops, giving overall complexity O(n).
Simple approach:
initialize a set with all the values you need. (In your case number 0 to n)
iterate over your arry and remove the number from the set
at the end the set is giving you the missing entries.
If you know that exactly one number is missing, there is a simple solution using xor.
static int missing(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++)
result ^= (i + 1) ^ arr[i];
return result;
}
If there may be more than one number missing you can return a Set like this:
static Set<Integer> missing(int[] arr) {
Set<Integer> set = new HashSet<>();
for (int i = 0; i <= arr.length; i++)
set.add(i);
for (int a : arr)
set.remove(a);
return set;
}
Here is a solution that utilizes one loop. That's if we choose to ignore what Arrays.sort does
import java.util.Arrays;
class Solution {
public int solution(int[] A) {
Arrays.sort(A);
int min = 1;
for (int i = 0; i < A.length; i++){
if(A[i]== min){
min++;
}
}
min = ( min <= 0 ) ? 1:min;
return min;
}
}
class Missing{
public static void main(String[] args) {
int arr[]={1,2,4,5,6,7,9};
System.out.println(missingNumberArray(arr));
}
public static int missingNumberArray(int [] a) {
int result=0;
for(int i=0;i<a.length-1;i++){
if(a[i+1]-a[i]!=1){
result=a[i]+1;
}
}
return result;
}
}
//output:missing element is:3
// missing element is:8

Repeat an integer n times

I'm trying to make a pyramid out of an integer.
I.E the number 3 :
3
33
333
So based on the answers i found i made this :
int n = 8;
String n2 = Integer.toString(n);
for (int i=0; i<n; i++) {
System.out.println(StringUtils.repeat(n2, i));
}
But it's not working and would be suboptimal. Is there a simple way to repeat an integer n times in the same line ?
EDIT : made myself a method.. not quite happy either but it seems i can't just use something like System.out.println(int x, int n times)
int n = 8;
for (int i=0; i<=n; i++) {
for (int j=0; j<i; j++) {
System.out.print(n + " ");
}
System.out.println("");
}
Ok, you can do this without explicit loops using Java-8 streams:
IntStream.range(1,n).forEach(i -> System.out.println(StringUtils.repeat(n2, i));
or even without apache-commons:
IntStream.range(0,n).forEach(i -> System.out.println(String.join("", Collections.nCopies(i+1, n2))));
But in any case internally all these methods use loops.
I mean isn't it suboptimal to convert my int into a string ? AIn't
there a direct way to deal with the integer ? –
If you dont want to convert int to string.
This may help you.
int n = 3;
for (int i=1; i<=n; i++) {
System.out.println(new String(new char[i]).replace("\0", n+""));
}
Something as below.
public class Test{
public static String repeat(String str, int times) {
return new String(new char[times]).replace("\0", str);
}
public static void main(String[] args) {
for (int i = 1; i < 5; i++) {
System.out.println(repeat("3", i));
}
}
}
Output
3
33
333
3333
You could try to use a StringBuilder.
You would still have to loop, but it might be slightly better performance-wise.
int n = 8;
String n2 = Integer.toString(n);
StringBuilder builder = new StringBuilder(n);
for(int i = 0; i < n; i++) {
builder.append(n2);
System.out.println(builder.toString());
}
This does what you want, but not in the way you think about it. Instead of repeatedly having to create the repeating integer string, we simply build ONE string, saving us the work of repeating it.
To actually answer your question, you could use this code, although I would recomend the first approach:
char[] str = new char[n];
Arrays.fill(str, (char)(number + '0'));
new String(str);
This would only work if your integer is 0 <= number < 10.
To keep with integers, you may store last value each time, and add the next part :
i = 0 --> you get 3
i = 1 --> you get 33 (i0 + 30)
i = 2 --> you get 333 (i1 + 300)
int lastValue = 0;
for (int i=0; i<=n; i++) {
int currentValue = lastValue + (n * Math.pow(10, i));
System.out.println(currentValue);
lastValue = currentValue ;
}
This obviously works for one-digit integers only.

Categories