I want to single out only positive numbers in one line and only negative numbers in one line, but they only show one by one with the text.
Here's my code:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.println("Less than 0: " + array[i]);
} else if (array[i] > 0) {
System.out.println("Greater than 0: " + array[i]);
}
}
You are currently printing a line for each element (and whether it is less than 0 or greater than 0), instead I would use an IntStream and filter() it for the desired elements (and collect those with Collectors.joining()). Like,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
System.out.println("Less than 0: " + IntStream.of(array) //
.filter(x -> x < 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
System.out.println("Greater than 0: " + IntStream.of(array) //
.filter(x -> x > 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
Outputs
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
You could achieve the same result with a pair of StringJoiner(s) a for-each loop and (just because) formatted io. Like,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
StringJoiner sjLess = new StringJoiner(", ");
StringJoiner sjGreater = new StringJoiner(", ");
for (int x : array) {
if (x < 0) {
sjLess.add(String.valueOf(x));
} else if (x > 0) {
sjGreater.add(String.valueOf(x));
}
}
System.out.printf("Less than 0: %s%n", sjLess.toString());
System.out.printf("Greater than 0: %s%n", sjGreater.toString());
Since you sorted the values, you know all negative values come before the positive values, so you start printing values and then switch to new line when you encounter the first positive value.
E.g. like below, which can also handle an array of all negative values, an array of all positive values, and even an empty array.
This only uses Java constructs you've already shown you know.
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0, iFirstPositive = 0; i < array.length; i++) {
if (array[i] < 0)
iFirstPositive = i + 1; // Assume index of first positive value is next
if (i == iFirstPositive) {
if (i != 0)
System.out.println(); // End line of negative values
System.out.print("Greater than 0: "); // Start line of positive values
} else if (i == 0) {
System.out.print("Less than 0: "); // Start line of negative values
} else {
System.out.print(", ");
}
System.out.print(array[i]);
}
if (array.length != 0) {
System.out.println(); // End line if anything printed
}
Output
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
Simpler, but slightly less optimal, you can also just do it with two loops:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
System.out.print("Less than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
System.out.print("Greater than 0:");
for (int i = 0; i < array.length; i++) {
if (array[i] > 0) {
System.out.print(" " + array[i]);
}
}
System.out.println();
Output
Less than 0: -50 -5 -2
Greater than 0: 2 4 12 54 150
Do something like this:
Arrays.sort(array);
String negative = "Less than 0: ";
String positive = "Greater than 0: ";
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
negative.concat(array[i] + ",");
}
else (array[i] > 0) {
positive.concat(array[i] + ",");
}
}
System.out.println(positive);
System.out.println(negative);
Store the values in a string and then print them after the for loop.
This is a perfect use case for streams:
System.out.println(Arrays.stream(array).filter(n -> n < 0).collect(Collectors.toList()));
I tried to change your code as little as possible.
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
boolean firstHalf = true;
System.out.print("Less than 0: ");
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.print(array[i] + " ");
} else if (array[i] > 0) {
if (firstHalf){
System.out.print("\nGreater than 0: ");
firstHalf = false;
}
System.out.print(array[i] + " ");
}
}
I think using of partitioningBy (that introduced in java 8) is exactly for this situation. you don't need to sort array too.
Map<Boolean,List<Integer>> map = IntStream.range(0,array.length)
.mapToObj(i->array[i])
.collect(Collectors.partitioningBy(a->a>0));
print positive number
map.get(true).forEach(integer -> System.out.print(integer+","));
print negative number
map.get(false).forEach(integer -> System.out.print(integer+","));
if you want to sort it you can do it like bellow.
map.get(false).stream().sorted()....
Related
I want to make a java program that asks for a number as input data and generates the following numerical series, the series must show the amount of numbers indicated by the user, but it will only be able to print the numbers from one to ten and then descending.
Input: 7
Output: 1, 2, 3, 4, 5, 6, 7
Input: 12
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9
Input: 22
Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1, 2
This is what I currently am working with:
System.out.print("Input number > ");
int number = sc.nextInt();
int j = 0;
boolean ascending = true;
for(int i = 1; i <= n4; i++){
if(ascending){
if(j >= 10){
j--;
ascending = false;
} else {
j++;
}
} else {
if (j <= 1){
j++;
ascending = true;
} else {
j--;
}
}
System.out.print(j + ", ");
}
The tricky bit in your sequence is that the limits (1 and 10) are printed twice. This means that there are not two, but three delta values in the sequence: +1, then 0, then -1. The following logic should be sufficient to produce the sequence:
int numLoops = sc.next();
int delta = +1;
int currentValue = 1;
StringBuilder result = new StringBuilder();
for (int i = 0; i < numLoops; i++) {
result.append(Integer.toString(currentValue) + ", ");
currentValue += delta;
if (currentValue >= 10) delta = (delta == 0) ? -1 : 0;
if (currentValue <= 1 ) delta = (delta == 0) ? +1 : 0;
}
System.out.println(result.toString());
Note that a StringBuilder instance is used to assemble the output rather than a series of calls to System.out. This is more stylish.
I'm told to implement two pointers which will run through the first and last index of my array and try to find a pair that returns 20.
If the pair's sum is larger than 20 then lower the last index by 1 and if the pair's sum is smaller than 20 then add the first index by 1. If the pair returns 20 find the smallest number's index.
This is my checkSum method:
public static int checkSum(int[] array){
// This function will inspect the input to find any pair of values that add up to 20
// if it finds such a pair, it will return the *index* of the smallest value
// if it does not find such as pair, it will return -1;
int twenty = 20;
int zero = 0;
int checkIndex = array.length;
for (int i = 0; i < array.length - 1; i++){
for (int k = array.length - 1; k < array.length; k++){
if (array[i] + array[k] == twenty){
// 0 + 1
System.out.println("this print out 20");
System.out.println(array [k] + " + " + array[i]);
if (array [k] >= array [zero]){
//need to print out the index of the minimum value
checkIndex = zero;
}
}
else if (array[i] + array[k] > twenty){
array[k]--;
checkIndex = array[k];
}
else if (array[i] + array[k] < twenty){
//tried a different method to see if it would increment the index rather than the value
array[i+1] = array[i];
checkIndex = array[i];
}
}
}// remove the following line after you are done writing the function
System.out.println(checkIndex);
return checkIndex;
}
and this is the main method that is provided:
public static void main(String[] args) {
int[] array1 = new int[]{5, 7, 8, 9, 10, 15, 16};
if (checkSum(array1) != 0){
System.err.println("TEST1 FAILED");
}
int[] array2 = new int[]{3, 5, 8, 9, 10, 15, 16};
if (checkSum(array2) != 1){
System.err.println("TEST2 FAILED");
}
int[] array3 = new int[]{3, 4, 6, 9, 10, 14, 15};
if (checkSum(array3) != 2){
System.err.println("TEST3 FAILED");
}
int[] array4 = new int[]{6, 7, 8, 9, 10, 15, 16};
if (checkSum(array4) != -1){
System.err.println("TEST4 FAILED");
}
System.out.println("Done!!!");
}
My error is that it's doing:
Lets say array[i] + array[k] > twenty:
expected output:
array[0] + array[6] = 5 + 16 > 20
so do array[0] + array[5] = 5 + 15 = 20
than notice that 5 < 15 so the index is 0.
current output:
array[6] + array [6] - 1 = 16 + 15 > 20
so array[6] - 1 + array [6] - 1 - 1 = 15 + 14 > 20
and so forth...
You don't need a nested loop to do the task. Assuming your input array is always sorted, you can declare two variables in one for loop one starting at the first element of your array and the second at the last element. Check at each step if the sum equals 20 if yes find the index and break the loop, if not increment your first variable or decrement your second variable depending on whether the sum was greater or less than 20.
public static int checkSum(int[] array) {
int checkIndex = -1;
int first = 0;
int last = array.length -1;
for (int i = first, k = last; i < k; ) {
if (array[i] + array[k] == 20){
System.out.println("Found a pair which adds up to 20");
System.out.println(array [i] + " + " + array[k]);
//find index of smallest value
if (array[i] < array[k]){
checkIndex = i;
}
else {
checkIndex = k;
}
//break out of loop if found a valid pair
break;
}
else {
//you will get here if the sum was not 20. Increment i or decrement k according to sum > 20 0r sum < 20
if (array[i] + array[k] > 20){
k--;
}
else {
i++;
}
}
}
System.out.println("index to return" + checkIndex);
return checkIndex;
}
I have a list of 16 numbers, and I want them set as variables n1-n16. I'm looking for something similar to How to assign each element of a list to a separate variable?, but for java.
My code is:
public void setVar()
{
//x = 16;
cardNumR = cardNum;
reversed = 0;
while(cardNumR != 0) {
digit = cardNumR % 10;
reversed = reversed * 10 + digit;
cardNumR /= 10;
}
ArrayList<Long> nums = new ArrayList<Long>(x);
for (int x = 16; x > 0; x--)
{
nums.add(reversed % 10);
reversed -= (reversed % 10);
reversed /= 10;
length = nums.size();
if (length == 16)
{
System.out.println(nums);
}
}
}
which gets me a result of:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
I want to take each of these elements and set n1 = 1, n2 = 2, n3 = 3 so on and so forth such that n16 = 6. I want to be able to do this at the end:
(2*n1) + n2 + (2*n3) + n4 + (2*n5) + n6 + (2*n7) + n8 + (2*n9) + n10 + (2*n11) + n12 + (2*n13) + n14 + (2*n15) + n16
Is there a way I can do this with a loop so that I don't have to do it one by one?
You don't need so many variables. Use a loop instead:
int sum = 0;
for(int i = 0; i < nums.size(); i++) {
if(i % 2 == 0) {
// odd index
sum += 2 * nums.get(i);
} else {
// even index
sum += nums.get(i);
}
}
Well I would just use an array
int [] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6};
or a list for that:
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6);
and apply the following formula:
Arrays
int result = 0;
for(int i = 0; i < array.length; i++) {
result += (i % 2 == 0) ? 2 * array[i] : array[i];
}
or if you want to avoid the use of the modulus (%) operation:
int result = 0
for(int i = 0; i < array.length; i+=2)
result += 2 * array[i];
for(int i = 1; i < array.length; i+=2)
result += array[i];
Lists
int result = 0;
for(int i = 0; i < nums.size(); i++) {
result += (i % 2 == 0) ? 2 * nums.get(i) : nums.get(i);
}
without the modulus operation :
int result = 0
for(int i = 0; i < nums.size(); i+=2)
result += 2 * nums.get(i);
for(int i = 1; i < nums.size(); i+=2)
result += nums.get(i);
Java Streams:
int result = IntStream.range(0, nums.size())
.mapToLong(i -> (i % 2 == 0) ? 2 * nums.get(i) : nums.get(i))
.sum();
Im trying to implement a linear search for an array of integers that if the number is a multiply of 3 its going to print the index of the number in the array and if there is no any number that is a multiple of 3 its going to return -1
im trying to implement this without using a method for it and my problem is how im going to do the printing/returning of -1?
knowing that my code is
int[] a = {3, 5, 22, 7, 9, 8, 21};
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
continue;
}
}
You could use a boolean found = false and set it to true if the algorithm found a multiply of 3. After the for loop you could ask for result.
int[] a = {3, 5, 22, 7, 9, 8, 21};
int multipleOfThree = 0;
System.out.println("the index of 3 multiplies is" );
for (int i = 0; i < a.length; i++) {
if (a[i] % 3 == 0) {
System.out.print(i + " ");
multipleOfThree++;
}
}
if( multipleOfThree == 0 ){
System.out.println(-1);
}
I think this is what you are looking for. If you want to use a method, instead of printing the multipleOfThree, you should return it.
int[] a = {1,5,22,7,52,8,20};
System.out.println("the index of 3 multiplies is" );
boolean found = false;
for(int i = 0; i<a.length;i++){
if(a[i]%3==0){
found = true;
System.out.println(i+" ");
}
}
if(!found){
System.out.println("-1");
}
}``
I want to find all the pairs of numbers from an array whose sum is equal to 10, and am trying to improve upon this bit of code here:
for (int j = 0; j < arrayOfIntegers.length - 1; j++)
{
for (int k = j + 1; k < arrayOfIntegers.length; k++)
{
int sum = arrayOfIntegers[j] + arrayOfIntegers[k];
if (sum == 10)
return j + "," + k;
}
}
However, I'm having trouble moving through the array. Here's what I have so far:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = arrayOfIntegers[0];
int right = (arrayOfIntegers[arrayOfIntegers.length - 1]);
while (left < right)
{
int sum = left + right;
if (sum == 10) //check to see if equal to 10
{
System.out.println(left + "," + right);
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
Try this code by passing the value of the sum and array in which you want to find the pair of elements equals to a given sum using one for loop
private void pairofArrayElementsEqualstoGivenSum(int sum,Integer[] arr){
List numList = Arrays.asList(arr);
for (int i = 0; i < arr.length; i++) {
int num = sum - arr[i];
if (numList.contains(num)) {
System.out.println("" + arr[i] + " " + num + " = "+sum);
}
}
}
You need to capture the values as well as the indexes:
int[] arrayOfIntegers = {0, 5, 4, 6, 3, 7, 2, 10};
Arrays.sort(arrayOfIntegers);
System.out.println(Arrays.toString(arrayOfIntegers));
int left = 0;
int right = arrayOfIntegers.length - 1;
while (left < right)
{
int leftVal = arrayOfIntegers[left];
int rightVal = (arrayOfIntegers[right]);
int sum = leftVal + rightVal;
if (sum == 10) //check to see if equal to 10
{
System.out.println(arrayOfIntegers[left] + "," + arrayOfIntegers[right]);
right --;
left++;
}
if (sum > 10) // if sum is more than 10, move to lesser number
{
right --;
}
if (sum < 10) // if sum is less than 10, move to greater number
{
left++;
}
} // end of while
output:
[0, 2, 3, 4, 5, 6, 7, 10]
0,10
3,7
4,6
This is sample code with javascrypt. Someone can use it
var arr = [0, 5, 4, 6, 3, 7, 2, 10]
var arr1 = arr;
for(var a=0; a<arr.length;a++){
for(var b=0; b<arr.length; b++){
if(arr[a]+arr[b]===10 && a!==b){
console.log(arr[a]+" + "+arr[b])
arr.splice(a,1);
}
}
}
Java - Using single loop
public static void findElements() {
List<Integer> list = List.of(0, 5, 4, 6, 3, 7, 2, 10);
for (int i = 0; i < list.size(); i++) {
int sum = 0;
if (i < list.size() - 1) {
sum = list.get(i) + list.get(i + 1);
if (sum == 10) {
System.out.println("Element: " + list.get(i) + "," + list.get(i + 1));
}
} else {
if (list.get(i) == 10) {
System.out.println("Element: " + list.get(i));
}
}
}
}