I have an array that contains [45,8,50,15,65,109,2]. i would like to check to see if the zero element of my array is greater than my first element.
if ( 45 > 8)
then i would like to add 45 to brand new sub array.
i would like to continue checking my array for anything that is bigger than 45 and add it to the new sub array.
The new sub array has to keep the numbers added in the way they where added.The result should be [45,50,65,109]
I thought by creating this was going in the right direction but im doing something wrong so please help.
int[] x = [45,8,50,15,65,109,2];
int[] sub = null;
for(int i = 0; i > x.length; i++) {
for(int k = 0; k > x.length; k++) {
if(x[i] > x[k]){
sub = i;
First thing first. Your question contains some errors.
you should write int[] x = {45,8,50,15,65,109,2}; instead of int[] x = [45,8,50,15,65,109,2]; You can not use [] to initialize array!
What does it mean for(int i = 0; i > x.length; i++). Your program must not run! Because, the value of i is less than x.langth. First condition check is false, so loop will not works!
Same for for(int k = 0; k > x.length; k++)
How do you want to store value in an array without index? You have to write sub[i] = x[i]; here, i means what index value you want to store where!
Finally, do you want to do sorting? If yes, then you need another variable named temp means temporary!
Try to clear the basic and after then try this code.Sorting Link
Best of Luck!
It is possible to filter the input array using Java 8 Stream API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x)
.filter(n -> n >= x[0])
.toArray();
System.out.println(Arrays.toString(sub));
Output:
[45, 50, 65, 109]
If you're trying to fetch everything greater than 0th element.
Use the following:
Plain old java code:
int[] x = {45,8,50,15,65,109,2};
int[] sub = new int[x.length];
int first = x[0];
sub[0]=first;
int index=1;
for(int i = 1; i < x.length; i++) {
if(x[i] > first){
sub[index]=x[i];
index++;
}}
Streams API:
int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x).filter(number -> number>=
x[0]).toArray();
where stream() is converting array to a stream, filter is applying the required condition and then ending it with conversion into an Array again.
Related
i am trying to formulate a for loop that will take an array, for instance of 5 elements, and will allow me to treat a[0] as if it is after a[4], and a[4] as if it was before a[0].
I cannot change the array, and it stores a thread in each element, so i would rather make it as simple as possible to not corrupt the contents of the thread(threads are synchornized and using reentrantlock - so the question is only about array).
I want to make this simple for loop:
for (int i = 0; i < ARRAYSIZE; i++)
to allow me to treat it as if it was a cyclic array. I thought of using the mudolo operation to achieve that, but that doesn't work either. here's what i tried:
for (int i = i+1 % n; i < ARRAYSIZE; i++)
but that doesn't work as well. What I am trying to do is basically check if array[i] is larger than array[i+1] or array[i-1].
would appreciate your assistance.
Use the modulo operator on the loop variable i by the size of the array:
public static void main(String [] args) {
int [] arr = {1, 5, 4, 3, 3, 4, 3, 1};
int ARRAYSIZE = arr.length;
for (int i = 0; i < ARRAYSIZE; i++) {
int index = i % ARRAYSIZE;
int indexUpper = (i + 1) % ARRAYSIZE;
//access array using index
if (arr[index] == arr[indexUpper]) {
System.out.format("Elements %d and %d are equals.\n", index, indexUpper);
}
}
}
Note how for the upper value you want to cycle through, you need to do (i + 1) % ARRAYSIZE to ensure you get the next element. To get the element two places over, add 2 instead, or whatever modifier you choose.
This test shows how elements 7 and 0 are equal because it is cyclical.
Output:
Elements 3 and 4 are equals.
Elements 7 and 0 are equals.
int timeTakenInSeconds[] = {600, -1, 500, 430, 412, -1, 0, 0, 0};
I want to sort this array from smallest to biggest. Simple, the problem is I need to ignore -1 and 0. My idea was to use a bubble sort to sort the array and place it in a new array. But I'm finding trouble sorting this array while ignoring 0 and -1.
Still a bit new to arrays, so I was wondering if anyone has suggestions?
I suggest you consider my compact solution (Java 8).
Arrays.stream(timeTakenInSeconds) // turn the array into the stream
.filter(i -> i != 0 && i != -1) // throw away 0 and -1
.sorted() // make a sorted order by default
.toArray(); // put into an array
The second part is similar to the first one. Then to merge 2 arrays you may use, for example, ArrayUtils.addAll(T[], T...) from Apache.
Filter, then apply your sort yourself:
int[] newArray = Arrays.stream(timeTakenInSeconds).filter(i -> i > 0).toArray();
customBubbleSort(newArray);
Here is a solution that sorts the array in place and doesn't require anything sophisticated from recent versions of Java.
public static void weirdSort(int arr[]) {
int zeros = 0;
int minusOnes = 0;
int index = 0;
for (int a : arr) {
switch (a) {
case 0:
zeros++;
break;
case -1:
minusOnes++;
break;
default:
arr[index++] = a;
}
}
for (int i = 0; i < zeros; i++)
arr[index++] = 0;
for (int i = 0; i < minusOnes; i++)
arr[index++] = -1;
Arrays.sort(arr, 0, arr.length - zeros - minusOnes); // Replace with bubble sort
}
EDIT Updated to sort positive integers in ascending order and integers less than or equal to 0 in descending order.
Using an Integer comparator:
int timeTakenInSeconds[] = {600, -1, 500, 430, 412, -1, 0, 0, 0};
Comparator<Integer> comparator = Integer::compare;
//split the positive and negative integers since they'll be sorted differently.
//Ascending order is the easiest.
int[] positiveInts = IntStream.of(timeTakenInSeconds).filter(i -> i > 0).sorted().toArray();
int[] negativeInts = IntStream.of(timeTakenInSeconds).filter(i -> i <= 0).toArray();
//And now for discending order for negative integers.
List<Integer> list = IntStream.of(negativeInts).boxed().collect(Collectors.toList());
Integer[] sortedNegative = list.stream().sorted(comparator.reversed()).toArray(Integer[]::new);
//Now overwrite timeTakenInSeconds with the correct values.
int i = 0;
for (int val : positiveInts) {
timeTakenInSeconds[i] = val;
i++;
}
for (int j = 0; j < sortedNegative.length; j++) {
timeTakenInSeconds[i] = sortedNegative[j];
i++;
}
Printing this with:
for (int j : timeTakenInSeconds) {
System.out.print(j + " ");
}
Sample run:
run:
412 430 500 600 0 0 0 -1 -1
BUILD SUCCESSFUL (total time: 0 seconds)
I am working on an assignment where we need to take a integer array and sort it using a Bucket Sort.
My issue comes when trying to increase to the next column, but only if there is an element already in the "bucket" already.
So, using my array below, 22 is the first element and will go in row 2 column 0, which is correct, but using i as the column is obviously not correct because it always increases the column and I eventually get an index out of bounds.
I can't wrap my head around how to correctly increase the index of the bucketArray column, only if there is an element in that position. I've tried using an additional for loop that handled the column but that didn't work either.
Any pointers in the right direction would be greatly appreciated! I'm sure also there are other ways to create a bucket sort but the assignment said to use a 2d array for each bucket so I was trying to get it to work that way.
public class BucketSort {
public static void main(String args[]) {
int intArray[] = {22, 45, 12, 8, 10, 6, 72, 81, 33, 18, 50, 14};
int eachBucket[][] = new int[10][11];
int j;
double max = 81;
int min = 6;
int divider = (int)Math.ceil((max + 1) / 10);
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][i] = intArray[i];
}
}
}
Use the 11th element to track how many elements in the current bucket have been used, something like this
for(int i = 0; i < intArray.length; i++) {
j = (int)Math.floor(intArray[i] / divider);
eachBucket[j][eachBucket[j][10]] = intArray[i];
eachBucket[j][10]++;
}
The problem with a fixed-sized second dimension is if you have more that n elements to put into any one bucket. Probably not a problem here.
I've had a decent search and am unable to find working code that moves down an array. What I am hoping to do, is to store the value in the last position in the array, replace the last position and then move array[20] to array[19]. This is meant to count the last 20 moves the player makes, but I'm having trouble actually storing. This is what I have attempted to do
//an int moveArray[20] previously stated and instantiated
int temp1, temp2;
for (int i = moveArray.length - 1; i > 0; i--)
{
temp1 = moveArray[i - 1];
temp2 = moveArray[i - 2];
moveArray[i - 1] = moveArray[i];
temp1 = temp2;
}
moveArray[moveArray.length - 1] = intoWalk;
any advice or solutions would really help, thanks
From what I understand of your code . You should use the following loop, there seems to be no need for temporary variables.
for(int i=0;i<moveArray.length-1;i++){
moveArray[i] = moveArray[i+1];
}
moveArray[moveArray.length - 1] = intoWalk;
First, you don't need to use temporary variables :
int [] moveArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int intoWalk = 21;
for (int i = 0; i < moveArray.length-1; i++) {
moveArray[i] = moveArray[i+1];
}
moveArray[moveArray.length - 1] = intoWalk;
for (int i=0; i<moveArray.length; i++)
System.out.println(moveArray[i]);
But there is a better way to do it : use a linked list to emulate a FIFO :
LinkedList<Integer> fifo = new LinkedList<Integer>();
int intoWalk = 21;
for (int i=1; i<=20; i++)
fifo.add(i);
fifo.removeFirst();
fifo.add(intoWalk);
for (Integer fifoItem : fifo)
System.out.println(fifoItem);
By doing this, you don't have to modify every element in your array each time you want to add a number, just to add and remove an item from the linked list.
//an int moveArray[20] previously stated and instantiated
int temp1, temp2;
temp1 = moveArray[moveArray.length - 1];
for (int i = moveArray.length - 2; i >= 0; i--)
{
temp2 = moveArray[i];
moveArray[i] = temp1;
temp1 = temp2;
}
moveArray[moveArray.length - 1] = intoWalk;
The above should do what you want.
However, I don't think this is the right way to go.
I would use the same array as a circular array - that way - you don't need to move down everytime.
Maintain a start index. It begins at
start = 0;
It remains at 0 till the time all 20 elements are filled up.
When the next element comes in,
moveArray[start] = intoWalk;
++start;
When you want to iterate through the array at any time, you begin at start instead of beginning at 0.
int i = start;
do
{
// do what you want
i = (i + 1)%20;
} while (i != start);
First make the last element free by moving all the elements one row down.
Sample :
String[] sarr=new String[10];
for(int i=0;i<sarr.length;i++){
sarr[i]=sarr[i+1];
}
Then assign the new variable to the end.
sarr[sarr.length-1]="new value";
This approach is simpler and more readable.
EDIT : Yes Bohemian is right it was throwing an ArrayIndexOutOfBounds exception. The reason was that i+1 will try to refer to an index out of the array's range at the last iteration.
The solution is either to set the last element to null or break when it's the last element.
I will go with setting the last element to null. The changed code is below.
int nextElementIndex = i + 1;
sarr[i] = nextElementIndex < sarr.length ? sarr[nextElementIndex] : null;
Background:
I have an N-length array of positive random numbers that are certain to contain duplicates.
e.g. 10,4,5,7,10,9,10,9,8,10,5
Edit: N is likely to be 32, or some other power of two about that size.
The Problem:
I am trying to find the fastest way to replace the duplicates with the missing numbers from 0-(N-1). Using the above example, I want a result that looks like this:
10,4,5,7,0,9,1,2,8,3,6
The goal being to have one of each number from 0 to N-1, without just replacing all the numbers with 0-(N-1) (the random order is important).
Edit: It's also important that this replacement is deterministic, i.e. the same input will have the same output (not random).
My solution:
Currently implemented in Java, uses 2 boolean arrays to keep track of used/unused numbers (unique numbers/missing numbers in the range [0,N) ), and has an approximate worst-case runtime of N+N*sqrt(N).
The code follows:
public byte[] uniqueify(byte[] input)
{
boolean[] usedNumbers = new boolean[N];
boolean[] unusedIndices = new boolean[N];
byte[] result = new byte[N];
for(int i = 0; i < N; i++) // first pass through
{
int newIdx = (input[i] + 128) % N; // first make positive
if(!usedNumbers[newIdx]) // if this number has not been used
{
usedNumbers[newIdx] = true; // mark as used
result[i] = newIdx; // save it in the result
}
else // if the number is used
{
unusedIndices[i] = true; // add it to the list of duplicates
}
}
// handle all the duplicates
for(int idx = 0; idx < N; idx++) // iterate through all numbers
{
if(unusedIndices[idx]) // if unused
for(int i = 0; i < N; i++) // go through all numbers again
{
if(!usedNumbers[i]) // if this number is still unused
{
usedNumbers[i] = true; // mark as used
result[i] = idx;
break;
}
}
}
return result;
}
This seems like the fastest I can hope for, but I thought I'd ask the internet, because there are people much more clever than I who may have a better solution.
N.B. Suggestions/solutions do not have to be in Java.
Thank you.
Edit: I forgot to mention that I am converting this to C++. I posted my java implementation because it's more complete.
Use a balanced binary search tree to keep track of used/unused numbers instead of a boolean array. Then you're running time will be n log n.
The most straightforward solution would be this:
Go through the list and build the "unused" BST
Go through the list a second time, keeping track of numbers seen so far in a "used" BST
If a duplicate is found, replace it with a random element of the "unused" BST.
Here is how I would write it.
public static int[] uniqueify(int... input) {
Set<Integer> unused = new HashSet<>();
for (int j = 0; j < input.length; j++) unused.add(j);
for (int i : input) unused.remove(i);
Iterator<Integer> iter = unused.iterator();
Set<Integer> unique = new LinkedHashSet<>();
for (int i : input)
if (!unique.add(i))
unique.add(iter.next());
int[] result = new int[input.length];
int k = 0;
for (int i : unique) result[k++] = i;
return result;
}
public static void main(String... args) {
System.out.println(Arrays.toString(uniqueify(10, 4, 5, 7, 10, 9, 10, 9, 8, 10, 5)));
}
prints
[10, 4, 5, 7, 0, 9, 1, 2, 8, 3, 6]
The fastest way to do this is probably the most straightforward one. I would take a pass through the list of data keeping a count of each distinct value and marking where duplicates appeared. Then it is just a matter of forming a list of unused values and applying them in turn at the places where duplicates were found.
Tempting as it may be to use a C++ List, if speed is of the essence a simple C array is the most efficient.
This program show the principle.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int data[] = { 10, 4, 5, 7, 10, 9, 10, 9, 8, 10, 5 };
int N = sizeof(data) / sizeof(data[0]);
int tally[N];
memset(tally, 0, sizeof(tally));
int dup_indices[N];
int ndups = 0;
// Build a count of each value and a list of indices of duplicate data
for (int i = 0; i < N; i++) {
if (tally[data[i]]++) {
dup_indices[ndups++] = i;
}
}
// Replace each duplicate with the next value having a zero count
int t = 0;
for (int i = 0; i < ndups; i++) {
while (tally[t]) t++;
data[dup_indices[i]] = t++;
}
for (int i = 0; i < N; i++) {
cout << data[i] << " ";
}
return 0;
}
output
10 4 5 7 0 9 1 2 8 3 6
My approach would be
1. copy the array to a Set in Java.
Set will automatically remove duplicates in the fastest complexity possible(because Sun Micro has implemented it, generally their approach is the fastest like.. use of TimSort for sorting etc...)
Calculate size() of the set.
the size will give you no of duplicates present.
now copy array 0-n-1 to the same set... the missing values will get inserted.
I think it is even possible with running time n. The idea is to keep track of items used in the original list and additional items used during processing in a separate array. A possible java implementation looks like this:
int[] list = { 10, 4, 5, 7, 10, 9, 10, 9, 8, 10, 5 };
boolean[] used = new boolean[list.length];
for (int i : list) {
used[i] = true;
}
boolean[] done = new boolean[list.length];
int nextUnused = 0;
Arrays.fill(done, false);
for (int idx = 0; idx < list.length; idx++) {
if (done[list[idx]]) {
list[idx] = nextUnused;
}
done[list[idx]] = true;
while (nextUnused < list.length && (done[nextUnused] || used[nextUnused])) {
nextUnused++;
}
}
System.out.println(Arrays.toString(list));
List<Integer> needsReplaced = newLinkedList<Integer>();
boolean[] seen = new boolean[input.length];
for (int i = 0; i < input.length; ++i) {
if (seen[input[i]]) {
needsReplaced.add(i);
} else {
seen[input[i]] = true;
}
}
int replaceWith = 0;
for (int i : needsReplaced) {
while (seen[replaceWith]) {
++replaceWith;
}
input[i] = replaceWith++;
}
This should behave in about 2n. The list operations are constant time, and even though that second loop looks nested, the outer loop runs significantly less than n iterations, and the inner loop will only run a total of n times.
C# but should be easy to convert to java. O(n).
int[] list = { 0, 0, 6, 0, 5, 0, 4, 0, 1, 2, 3 };
int N = list.length;
boolean[] InList = new boolean[N];
boolean[] Used = new boolean[N];
int[] Unused = new int[N];
for (int i = 0; i < N; i++) InList[list[i]] = true;
for (int i = 0, j = 0; i < N; i++)
if (InList[i] == false)
Unused[j++] = i;
int UnusedIndex = 0;
for (int i = 0; i < N; i++)
{
if (Used[list[i]] == true)
list[i] = Unused[UnusedIndex++];
Used[list[i]] = true;
}
Edit: tried to convert it to java from c#. I don't have java here so it may not compile but should be easy to fix. The arrays may need to be initialized to false if java doesn't do that automatically.