For example if I enter inRange(1,6) then it must print {2,2,2,3,5} for the below array. I am not sure if my logic is right. Is there a better way to do this? I am also not sure of how to construct my return statement. I want to do this without using arraylist or array.
public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount(){
}
public static int inRange(int b,int e)
{
int store[]=new int[a.length];
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]>b && a[i]<e)
{
return a[i];
}
}
return 0;
}
If your method only has to print the numbers of the given range, it doesn't have to return anything :
public static void inRange(int b,int e)
{
int count=0;
System.out.print('{');
boolean first = true;
for (int i = 0; i < a.length; i++) {
if(a[i]>=b && a[i]<=e)
{
if (!first) {
System.out.print(',');
} else {
first = false;
}
System.out.print(a[i]);
}
}
System.out.print('}');
}
This is assuming the order of the output doesn't matter. If it does matter, sort the input array prior to the loop.
Java 8 approach:
int[] arr = new int[] {1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
int res[] = Arrays.stream(arr).filter(n -> n >= b && n <= e).toArray();
System.out.println(Arrays.toString(res));
I'm not sure why you don't want to use arrays or some kind of a list. If it's for homework purposes, then instead of returning a value from the method, print it if you only want to display the result. Otherwise, you should consider using List.
Java8:
public static void main(String[] args) {
int[] arrayToFilter = new int[]{1, 2, 45, 6, 3, 2, 1, 2, 5, 6, 65, 45, 43, 21, 34, 34};
int upperLimit = 5;
inRange(arrayToFilter, upperLimit);
}
private static void inRange(int[] arrayToFilter, int upperLimit) {
String sortedAndLimitedString = Arrays.stream(arrayToFilter)
.sorted()
.filter(value -> value < upperLimit)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",", "{", "}"));
System.out.println(sortedAndLimitedString);
}
Output:
{1,1,2,2,2,3}
This sounds like a homework question. Still here goes.
Your return being a single int it has to be something like 122235 which represents all the ints satisfying your range condition.
So you use BitSet class and set the bits when found in range, which you can convert to an int like above and return.
I assumed that the result must be sorted.
public static int[] inRange(int b,int e) {
return IntStream.of(a)
.filter(n -> n > b && n < e)
.sorted()
.toArray();
}
System.out.println(Arrays.toString(AgeCount.inRange(1, 6)));
// -> [2, 2, 2, 3, 5]
```
Here is the simple & the shortest solution.
import java.util.*;
public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount()
{
}
public static void inRange(int b,int e)
{
int store[]=new int[a.length];
Arrays.sort(a);
for (int i = b; i < e; i++)
{
System.out.print(a[i+1]+",");
}
}
}
And this is how you return a value for the same.
//sort an array, get a defined index values, and print it on the screen.
import java.util.*;
public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount()
{
}
public static int[] inRange(int b,int e)
{
int store[]=new int[a.length];
int[] myRange = new int[e-b];
Arrays.sort(a);
for (int i = b; i < e; i++)
{
for (int j = 0; j < (e-b); j++)
{
myRange[j] = a[i+1];
}
System.out.print(a[i+1]+",");
}
return myRange;
}
}
Nice start so far! Even though you said you didn't want to use array or ArrayList, it makes the most sense here to use one. I would use an ArrayList of Integers instead of just an array, because we don't know the length yet. Instead of saying return a[i];, you would say store.append(a[i]);. I haven't tested this code, so there may be an error or two, so please correct me if I'm wrong, but here's the fixed version:
public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
public AgeCount(){
}
public static void inRange(int b,int e)
{
ArrayList<Integer> store = new ArrayList<Integer>();
int count=0;
for (int i = 0; i < a.length; i++) {
if(a[i]>=b && a[i]<=e)
{
store.append(a[i]);
}
}
println(store);
}
}
Well first things first, it seems like you aren't fully clear on what you are trying to do. And that's okay! Sometimes a problem can seem overwhelming and confusing if we're not really sure what's supposed to happen.
I recommend when you're starting a new task you take some time to decompose the task. Take a piece of paper and try and break it down into its smallest and simplest parts and go from there, coding and testing it bit by bit. The basics of the SDLC (try googling the software development lifecycle) could help you here too - it's all about figuring out what you are trying to achieve and what are the various things you need to implement to get there.
And please, Don't panic and throw code you don't understand down! You'll only sink deeper into the confusion!
Related
I'm trying to solve the two sum algorithm on Leetcode:
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
And came up with this:
public class Leet {
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{1, 2, 3, 4, 5, 6}, 2)));
}
public static int[] twoSum(int[] nums, int target) {
int[] answer = null;
int i = 0;
for (int j = nums[i]; i < nums.length; i++) {
for (int x : nums) {
if (x != j & (j + x) == target) {
int x2 = java.util.Arrays.asList(nums).indexOf(x);
answer[0] = i;
answer[1] = x2;
} else {
return nums;
}
}
}
System.out.println("leet method executed");
return answer;
}
}
The problem is it's not returning anything, not event the printed statement. Any ideas?
See some fixes. Remember about array initialization and cases when values can be same in the array.
public class Solution {
public int[] twoSum(int[] nums, int target) {
int[] answer = null;
for(int i=0;i<nums.length;i++) {
int value = nums[i];
for(int j=i+1;j<nums.length;j++) {
int x=nums[j];
if ((value+x)==target) {
answer = new int[2];
answer[0]=i;
answer[1]=j;
}
}
}
System.out.println("leet method executed");
if (answer == null) {
return nums;
}
return answer;
}
}
I can see 2 things wrong or not intended in the program (leaving aside whether it's the best approach to the problem).
As stated in a comment, you should use && instead of & for boolean AND. & is bitwise AND, useful for integer bit twiddling.
You declare answer as an array, but never create space for it. You need to say int [] answer = new int[2]; or similar.
I haven't run the code, but if the test program ends with no output, check that you aren't getting a NullPointerException (caused by #2 above).
Don't forget about null-checks and the case where no correct number-pair was found.
public static int[] twoSum(int[] numbers, int target) {
if(Objects.isNull(numbers)){
throw new IllegalArgumentException("numbers is not allowed to be null");
}
for (int a=0;a<numbers.length;a++) {
int first = numbers[a];
for (int b=0;b<numbers.length;b++) {
int second = numbers[b];
if (first + second == target && a!=b) {
return new int[] { first, second };
}
}
}
throw new IllegalArgumentException("there has to be a matching pair");
}
I'm trying to return the positive numbers in an array. I'm new to arrays and am having trouble figuring it out.
public class PossitiveArray
{
public static void main(String[] args) {
int[] numbers = {2,-1,5,-4,3};
System.out.print(numbers);
}
public static int[] getPositiveNumbers(int[] numbers)
{
for (int n : numbers)
{
if(n>0)
{
int [] nums = numbers;
}
}
return nums;
}
}
Analysis-
This is what I came up with. As it is right now it gives me and error saying I need to make a local variable for nums but when I do that it returns "[I#677327b6". I tried to make it return numbers but i'm not sure what to put into the if statement.
Required-
The goal is to just have positive numbers returned. Any help would be appreciate I am very knew to arrays and programing in general.
Java 8's streams would make this take much easier:
public static int[] getPositiveNumbers(int[] numbers) {
return Arrays.stream(numbers).filter(i -> i > 0).toArray();
}
Regarding printing the result - you're seeing the default toString(), as int[] does not override it. Instead, you could use Arrays.toString to print the result.
Use below Code-
public class test
{
public static void main(String[] args) {
int[] numbers = {2,-1,5,-4,3};
for(int n : getPositiveNumbers(numbers)){
System.out.print(n);
}
}
public static int[] getPositiveNumbers(int[] numbers)
{
int count = 0;
for (int n : numbers)
{
if(n>0)
{
count++;
}
}
int [] nums = new int[count];
int i =0;
for (int n : numbers)
{
if(n>0)
{
nums[i] = n;
i++;
}
}
return nums;
}
}
There are a few things to consider here to answer your question.
Variable scope of nums is local to the loop. This means that nums will be deleted each time the for-loop iterates, and will be gone when the loop ends. You can address this by moving the declaration to before the for-loop.
Your declaration int[] nums only declares that nums is an array of ints, but doesn't allocate any space to put anything into the array. You must allocate the space using for example int[] nums = new int[5], which creates an array of 5 slots. In your case, you'll want an array that will hold all the positive numbers, which at most will be the entirety of the input array. Use int [] nums = new int[numbers.length] to accomplish this (but see next point).
How do you want to fill the new array nums containing only the positive integers? The way you have it written it looks like you would like {2,-1,5,-4,3} to return {2, 5, 3}, or would you rather it return {2,0,5,0,3}. Either case will affect how your for-loop should handle nums. For an output of {2, 5, 3} the size of the array needs to figured out beforehand by counting the number of positive entries first.
NOTE: This problem could be solved more easily using linked lists, where size is handled dynamically.
Here is a solution that replaces negatives with zeros.
class PossitiveArray {
public static void main(String[] args)
{
int[] numbers = {2,-1,5,-4,3};
System.out.print(Arrays.toString(getPositiveNumbers(numbers)));
}
public static int[] getPositiveNumbers(int[] numbers)
{
int [] nums = new int[numbers.length];
for(int i = 0; i < numbers.length; i++)
{
if(numbers[i] > 0)
{
nums[i] = numbers[i];
}
else
{
nums[i] = 0;
}
}
return nums;
}
}
I am attempting to sort an array of integers such that all even numbers precede odd numbers, without using any external libraries.
You may recognize this from: http://codingbat.com/prob/p105771
" Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You may modify and return the given array, or make a new array. "
I have code that accomplishes this goal:
public int[] evenOdd(int[] nums) {
int c=0;
int c2=0;
int [] nums2=new int[nums.length];
for(int i=0;i<nums.length;i++)
{
if(nums[i]%2==0)
{
nums2[c]=nums[i];
c++;
}
else
{
nums2[nums.length-c2-1]=nums[i];
c2++;
}
}
return nums2;
}
I have also approached the problem by calling array.sort() and then inserting the numbers by index, incrementing by two, then inserting the remainder. This also works.
So, to make a long post short-is there a more elegant way to accomplish this goal in future?
Thanks!
Just a follow-up to my comment. Here is how you can do it in O(n) without extra-space:
public class Main {
public static void main(String[] args) {
evenOdd(new int[]{1, 2, 3, 4, 5, 6, 7});
evenOdd(new int[]{2, 3, 4, 5, 6, 7});
evenOdd(new int[]{1, 1, 1, 1, 1});
evenOdd(new int[]{2, 2, 2, 2});
}
public static void evenOdd(int[] a) {
int firstOdd = 0;
for (int i = 0; i < a.length; ++i) {
if (a[i] % 2 == 0) {
int t = a[firstOdd];
a[firstOdd] = a[i];
a[i] = t;
firstOdd++;
// } else {
// else is redundant, just leave odd in-place
}
}
System.out.println(Arrays.toString(a));
}
}
Create a wrapper object that contains an int, call it SortingWrapper. This object should implement Comparable, such that its natural sort order is based on the sort order of value%2. Then just sort the array with Arrays.sort(). Based on the compareTo() implementation, the evens will naturally (ie, according to their natural sort order) bubble one way, all the odds will bubble the other.
Alternatively, you could just uses Integers as your wrapper and pass a Comparator that does the same thing to Arrays.sort().
edit- here is the general idea. You might have to play around with the sort order, but I think this pretty much works. I suspect that this array will count as "mostly sorted" which would make performance tend more towards O(n) than log(n), based upon the javadoc for Arrays.sort().
public void sortOddsAndEvents(Integer[] input)
{
Arrays.sort(input, new Comparator<Integer>()
{
#Override
public int compare(Integer arg0, Integer arg1)
{
if (arg0.equals(arg1)) return 0;
else return Integer.compare(arg0.intValue()%2, arg1.intValue()%2);
}
});
}
public int[] evenOdd(int[] nums) {
int evenCounter = -1, oddCounter = nums.length;
int[] ordered = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
int current = (nums[i] % 2 == 0) ? ++evenCounter : --oddCounter;
ordered[current] = nums[i];
}
return ordered;
}
I'm writing a code where I have an int[a] and the method should return the number of unique values. Example: {1} = 0 different values, {3,3,3} = 0 different values, {1,2} = 2 different values, {1,2,3,4} = 4 different values etc. I am not allowed to sort the array.
The thing is that my method doesn't work probably. There is something wrong with my for statement and I can't figure it out.
public class Program
{
public static void main(String[] args)
{
int[] a = {1, 2, 3, 1};
System.out.println(differentValuesUnsorted(a));
//run: 4 //should be 3
}
public static int differentValuesUnsorted(int[] a)
{
int values; //values of different numbers
if (a.length < 2)
{
return values = 0;
}else if (a[0] == a[1])
{
return values = 0;
}else
{
values = 2;
}
int numberValue = a[0];
for (int i = a[1]; i < a.length; i++)
{
if (a[i] != numberValue)
{
numberValue++;
values++;
}
}
return values;
}
}
Can anybody help?
This is actually much simpler than most people have made it out to be, this method works perfectly fine:
public static int diffValues(int[] numArray){
int numOfDifferentVals = 0;
ArrayList<Integer> diffNum = new ArrayList<>();
for(int i=0; i<numArray.length; i++){
if(!diffNum.contains(numArray[i])){
diffNum.add(numArray[i]);
}
}
if(diffNum.size()==1){
numOfDifferentVals = 0;
}
else{
numOfDifferentVals = diffNum.size();
}
return numOfDifferentVals;
}
Let me walk you through it:
1) Provide an int array as a parameter.
2) Create an ArrayList which will hold integers:
If that arrayList DOES NOT contain the integer with in the array
provided as a parameter, then add that element in the array parameter
to the array list
If that arrayList DOES contain that element from the int array parameter, then do nothing. (DO NOT ADD THAT VALUE TO THE ARRAY LIST)
N.B: This means that the ArrayList contains all the numbers in the int[], and removes the repeated numbers.
3) The size of the ArrayList (which is analogous to the length property of an array) will be the number of different values in the array provided.
Trial
Input:
int[] numbers = {3,1,2,2,2,5,2,1,9,7};
Output: 6
First create distinct value array, It can simply create using HashSet.
Then alreadyPresent.size() will provide number of different values. But for the case such as -{3,3,3} = 0 (array contains same elements); output of alreadyPresent.size() is 1. For that use this simple filter
if(alreadyPresent.size() == 1)){
return 0;
}
Following code will give the count of different values.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args)
{
int array[] = {9,9,5,2,3};
System.out.println(differentValuesUnsorted(array));
}
public static int differentValuesUnsorted(int[] array)
{
Set<Integer> alreadyPresent = new HashSet<Integer>();
for (int nextElem : array) {
alreadyPresent.add(nextElem);
}
if(alreadyPresent.size() == 1){
return 0;
}
return alreadyPresent.size();
}
}
You can use a HashSet, which can only contain unique elements. The HashSet will remove the duplicated items and you can then get the size of the set.
public static int differentValuesUnsorted(int[] a) {
Set<Integer> unique = new HashSet<Integer>();
for (int val : a) {
unique.add(val); // will only be added if a is not in unique
}
if (unique.size() < 2) { // if there are no different values
return 0;
}
return unique.size();
}
For small arrays, this is a fast concise method that does not require the allocation of any additional temporary objects:
public static int uniqueValues(int[] ids) {
int uniques = 0;
top:
for (int i = 0; i < ids.length; i++) {
final int id = ids[i];
for (int j = i + 1; j < ids.length; j++) {
if (id == ids[j]) continue top;
}
uniques++;
}
return uniques;
}
Try this:
import java.util.ArrayList;
public class DifferentValues {
public static void main(String[] args)
{
int[] a ={1, 2, 3, 1};
System.out.println(differentValuesUnsorted(a));
}
public static int differentValuesUnsorted(int[] a)
{
ArrayList<Integer> ArrUnique = new ArrayList<Integer>();
int values=0; //values of different numbers
for (int num : a) {
if (!ArrUnique.contains(num)) ArrUnique.add(num);
}
values = ArrUnique.size();
if (values == 1) values = 0;
return values;
}
}
input:{1,1,1,1,1} - output: 0
input:{1,2,3,1} - output: 3
Try this... its pretty simple using ArrayList. You don't even need two loop. Go on
import java.util.*;
public class distinctNumbers{
public static void main(String []args){
int [] numbers = {2, 7, 3, 2, 3, 7, 7};
ArrayList<Integer> list=new ArrayList<Integer>();
for(int i=0;i<numbers.length;i++)
{
if(!list.contains(numbers[i])) //checking if the number is present in the list
{
list.add(numbers[i]); //if not present then add the number to the list i.e adding the distinct number
}
}
System.out.println(list.size());
}
}
Try this simple code snippet.
public static int differentValuesUnsorted(int[] a)
{
ArrayList<Integer> list=new ArrayList<Integer>(); //import java.util.*;
for(int i:numbers) //Iterate through all the elements
if(!list.contains(i)) //checking for duplicate element
list.add(i); //Add to list if unique
return list.size();
}
What about this?
private <T> int arrayDistinctCount(T[] array) {
return Arrays.stream(array).collect(Collectors.toSet()).size();
}
Use a set to remove duplicates
public static int differentValuesUnsorted(int[] a) {
if (a.length < 2) {
return 0;
}
Set<Integer> uniques = new HashSet<>(a);
return singleUnique.size();
}
I'm writing a module to handle dice rolling. Given x die of y sides, I'm trying to come up with a list of all potential roll combinations.
This code assumes 3 die, each with 3 sides labeled 1, 2, and 3. (I realize I'm using "magic numbers" but this is just an attempt to simplify and get the base code working.)
int[] set = { 1, 1, 1 };
list = diceroll.recurse(0,0, list, set);
...
public ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
dump(set);
recurse(index+1, i, list, set);
}
}
return list;
}
(dump() is a simple method to just display the contents of list[]. The variable i is not used at the moment.)
What I'm attempting to do is increment a list[index] by one, stepping through the entire length of the list and incrementing as I go.
This is my "best attempt" code. Here is the output:
Bold output is what I'm looking for. I can't figure out how to get rid of the rest. (This is assuming three dice, each with 3 sides. Using recursion so I can scale it up to any x dice with y sides.)
[1][1][1] [1][1][1]
[1][1][1] [1][1][2] [1][1][3] [1][2][3]
[1][2][1] [1][2][2] [1][2][3] [1][3][3]
[1][3][1] [1][3][2] [1][3][3] [2][3][3] [2][1][3]
[2][1][1] [2][1][2] [2][1][3] [2][2][3]
[2][2][1] [2][2][2] [2][2][3] [2][3][3]
[2][3][1] [2][3][2] [2][3][3] [3][3][3] [3][1][3]
[3][1][1] [3][1][2] [3][1][3] [3][2][3]
[3][2][1] [3][2][2] [3][2][3] [3][3][3]
[3][3][1] [3][3][2] [3][3][3]
I apologize for the formatting, best I could come up with.
Any help would be greatly appreciated. (This method was actually stemmed to use the data for something quite trivial, but has turned into a personal challenge. :)
edit: If there is another approach to solving this problem I'd be all ears, but I'd also like to solve my current problem and successfully use recursion for something useful.
edit2:
Running code including the "easy fix." Beware unused variables and weird hacks, I haven't cleaned it up yet.
package code.testing;
import java.util.ArrayList;
public class CodeTesting {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
int[] set = { 1, 1, 1 };
list = recurse(0,0, list, set);
}
public static ArrayList<Integer> recurse(int index, int i, ArrayList<Integer> list, int[] set){
if(index < 3){
// System.out.print("\n(looping on "+index+")\n");
for(int k=1;k<=3;k++){
// System.out.print("setting i"+index+" to "+k+" ");
set[index] = k;
if (index==2){
dump(set);
}
recurse(index+1, i, list, set);
}
}
return list;
}
static void dump(int[] arr) {
for (int s : arr) {
System.out.format("[%s]", s);
}
System.out.println();
}
}
I'm sorry I had to rewrite the code, but it's pretty much the same algorithm as yours with some corrections:
public class DiceRolls {
static void recurse(int diceNumber, int[] values, final int MAX) {
if (diceNumber == values.length) {
System.out.println(java.util.Arrays.toString(values));
} else {
for (int v = 1; v <= MAX; v++) {
values[diceNumber] = v;
recurse(diceNumber + 1, values, MAX);
}
}
}
public static void main(String[] args) {
recurse(0, new int[3], 4);
}
}
This is a standard tuplet recursive generator. If you want to add all the int[] into a List, then make sure to add(values.clone()) so they are independent int[] objects.
But what's with the extra output?
The problem is that you were dumping prematurely, before you're done throwing all the dices. In pseudocode, this is what you're doing:
if we're not done yet
trying all possibilities for this dice
dump result so far // premature dumping!
recurse for next dice
An easy fix to your code is to do the following:
if we're not done yet
trying all possibilities for this dice
recurse for next dice
else, we're done, so
dump result // timely!
So back to the Java implementation, the fix is merely moving dump(set); to an else case for the if (index < 3) statement.
Call dump() only when index == 2.
Incidentally, i and list seem unused. And the verb is "recur". :)
Here is a non-recursive alternative. Change the two constants to calculate all combinations for different dices and different numbers of dice.
package utils;
public class Dice {
private static int FACES = 3;
private static int NUMBER_OF_DICE = 3;
public static void main(String[] args) {
int start = createPair(1);
int end = createPair(FACES);
for (int i = start; i <= end; i++) {
String combination = Integer.toString(i, FACES+1);
if (combination.indexOf('0') < 0)
System.out.println(combination);
}
}
private static int createPair(int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < NUMBER_OF_DICE; i++) {
sb.append(number);
}
return Integer.parseInt(sb.toString(), FACES+1);
}
}