I am making a function that can turn a number into a simplified radical square root. I have so far made a function that can return the factors of a number. I want to turn the string into an array so I can index through the numbers in a for loop and test if they have a perfect square root. How can I do this?
This is what I have so far:
public static void factor(int num) {
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
System.out.println(i);
}
}
}
inputing the number 20 outputs
1
2
4
5
10
20
I want to turn this into {1, 2, 4, 5, 10, 20}
You can store them in a List when you print.
public static void factor(int num) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
list.add(i);
System.out.println(i);
}
}
//iterate over the list
for(int val: list){
//do something with val
}
}
However if you only want to convert a multi-line string to an array, do
yourMultiLineString.split("\n");
Read using a Scanner, store in a List, then use the .toArray() method.
List<Integer> l = new ArrayList<>();
Scanner sc = new Scanner(System.in);
for(int i = 0; i < 7; i++){
l.add(Integer.parseInt(sc.nextLine()));
}
int[] arr = (int[]) l.toArray();
You need to create a list of integers and push your data into it just like the list in below code:
public static void factor(int num) {
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= num; ++i) {
if (num % i == 0) {
list.add(i);
}
}
for(Integer i: list) {
System.out.println(i);
}
// OR via indexing
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
}
Related
i'm making a method that ignores multiples. The input is..
int[] Eliminate = new int[]{1, 54, 20, 17, 60};
this is the code..
public static int[] EliminateMultiples(int[] List, int Num) {
int[] New = new int[List.length];
int NewListIndex = 0;
for (int i=0; i<List.length; i++) {
if ((List[i] % Num !=0 )) {
New[NewListIndex] = List[i];
}
NewListIndex++;
System.out.println(New[i]);
}
return New;
}
The problem i'm getting is that the output has zeros in it. I think it's because I made the length of the new list to the old list even though the new list would maybe not have as many numbers.
Here is solution that will make you an array that is right size. It is different from because NewListIndex is putted into if, and in the end array is "trimed" to be right length.
public static int[] EliminateMultiples(int[] List, int Num) {
int[] New = new int[List.length];
int NewListIndex = 0;
for (int i=0; i<List.length; i++) {
if ((List[i] % Num !=0 )) {
New[NewListIndex] = List[i];
NewListIndex++;
}
}
int [] ret=Arrays.copyOfRange(New, 0, NewListIndex);
return ret;
}
Simple solution with Java 8 Streams:
public static int[] eliminateMultiples(int[] list, int num) {
return Arrays.stream(list).filter(i -> i % num != 0).toArray();
}
If you also want to print each element, you can peek into the stream and print them:
public static int[] eliminateMultiples(int[] list, int num) {
return Arrays.stream(list).filter(i -> i % num != 0).peek(System.out::println).toArray();
}
If you really need to use arrays, you need at least 2 loops:
Counting the number of elements:
int count = 0;
for (int element : list) {
if (element % num != 0)
count++;
}
Creating the array with the number of elements (from 1.) and filling it.
int[] result = new int[count];
int i = 0;
for (int element : list) {
if (element % num != 0) {
result[i++] = element;
}
}
return result;
As you can see, this is a lot more to write.
This program is giving output for all non-repeated elements but I need first one non-repeated element. I tried to keep if(flag==1) to break loop after the end of j loop, then I tested but it is not working for all cases
import java.util.Scanner;
public class first
{
public static void main(String[] args)
{
int n, flag = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Non repeated first element is :");
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(i != j)
{
if(a[i]!= a[j])
{
flag = 1;
}
else
{
flag = 0;
break;
}
if(flag == 1)
{
System.out.print(" ");
System.out.println(a[i]);
break;
}
}
}
}
}
}
You can construct two sets, singleSet and repeatedSet, respectively for elements appeared once and more than once. They can be created by doing one iteration on elements. Then, you do an a second iteration, to query which is the first element non-repeated:
int[] elements = { 1, 1, 2, 3, 3, 4 };
Set<Integer> singleSet = new HashSet<>();
Set<Integer> repeatedSet = new HashSet<>();
for (int e : elements) {
if (repeatedSet.contains(e)) {
continue;
}
if (singleSet.contains(e)) {
singleSet.remove(e);
repeatedSet.add(e);
} else {
singleSet.add(e);
}
}
for (int e : elements) {
if (singleSet.contains(e)) {
return e;
}
}
This solution is a O(n) solution, it should be faster than the nested-loop, which is O(n^2).
You can also replace the singeSet by a singleList, and at the end, return the first element in the singleList, which avoid the 2nd iteration on elements. Thus the solution is even faster.
Following up on the idea of the two sets from #Mincong, I am adding here the solution he mentioned as faster.
int[] array = { 1, 1, 2, 3, 3, 4 };
Set<Integer> allValues = new HashSet<>(array.length);
Set<Integer> uniqueValues = new LinkedHashSet<>(array.length);
for (int value : array) {
if (allValues.add(value)) {
uniqueValues.add(value);
}
else {
uniqueValues.remove(value);
}
}
if (!uniqueValues.isEmpty()) {
return uniqueValues.iterator().next();
}
First non-repeating integers in an array in Python
def non_repeating(arr):
non_repeating = []
for n in arr:
if n in non_repeating:
non_repeating.pop(non_repeating.index(n))
else:
non_repeating.append(n)
return non_repeating[0] if non_repeating else None
print(non_repeating([1, 1, 1, 5, 2, 1, 3, 4, 2]))
Javascript
function nonRepeatinInteger(arr) {
let val = [], count = [];
arr.forEach((item, pos) => {
if (!val.includes(item)) {
val.push(item);
count[val.indexOf(item)] = 1;
} else {
count[val.indexOf(item)]++;
}
});
return val[count.indexOf(Math.min(...count))];
}
console.log(nonRepeat([-1, 2, -1, 3, 2]));
console.log(nonRepeat([9, 4, 9, 6, 7, 4]));
private int getFirstNonRepeating(int[] arr) {
Set<Integer> set = new HashSet<>();
ArrayList<Integer> list = new ArrayList<>();
int min = 0;
for (int i = 0; i <arr.length; i++) {
//Parsing though array and adding to list if set.add returns false it means value is already available in set
if (!set.add(arr[i])) {
list.add(arr[i]);
}
}
//Parsing though array and checking if each element is not available in set,then that is smallest number
for (int i = 0; i < arr.length; i++) {
if (!list.contains(arr[i])) {
min = arr[i];
break;
}
}
Log.e(TAG, "firstNonRepeating: called===" + min);
return min;
}
Try this :
int a[] = {1,2,3,4,5,1,2};
for(int i=0; i<a.length;i++) {
int count = 0;
for(int j=0; j<a.length;j++) {
if(a[i]==a[j] && i!=j) {
count++;
break;
}
}
if(count == 0) {
System.out.println(a[i]);
break; //To display first non repeating element
}
}
def solution(self, list):
count_map = {}
for item in list:
count_map[item] = count_map.get(item, 0) + 1
for item in list:
if count_map[item] == 1:
return item
return None
Using JS Object:
function nonRepeat_Using_Object(arr) {
const data = arr.reduce((acc, val) => {
if (!acc[val]) {
acc[val] = 0;
}
acc[val]++;
return acc;
}, {});
for (let i = 0; i < arr.length; i++) {
if (data[arr[i]] === 1) {
return arr[i];
}
}
}
Another way to achieve this : you can use a hashmap to store counts of integers in the first pass and return the first element whose count is 1 in the second pass.
Here is a python code trying to achieve the same -
def singleNumber(nums: List[int]) -> int:
from collections import defaultdict
memory = defaultdict(int)
for num in nums:
memory[num] += 1
for k,v in memory.items():
if v == 1:
return k
I've tried to print the non-intersection of sets between 2 array A and B. But, I have a problem how to print the elements on A different B.
Here is my sample code:
public class Array {
public static void main(String[] args) {
for (int i = 0; i <= arrA.length - 1; i++) {
arrA[i] = sc.nextInt();
}
for (int i = 0; i <= arrB.length - 1; i++) {
arrB[i] = sc.nextInt();
}
boolean x = true;
int y = 0;
for (int i = 0; i < arrA.length; i++) {
for (int j = 0; j < arrB.length; j++) {
if (arrA[i] == arrB[j]) {
arrTestA[i] = true;
}else y = arrA[i];
}
}
for (int i = 0; i < arrA.length; i++) {
x = x && arrTestA[i];
}
if (x) {
System.out.println("All the elements of A contained in B.");
}else {
System.out.println("There are elements on A different B.");
System.out.println("The elements of A which is not in B = "); //My Problem
}
}
}
To accomplish that you could use Collections and retainAll method.
E.g.:
List<Integer> arrTestA = new ArrayList<>();
List<Integer> arrTestB = new ArrayList<>();
[...]
List<Integer> common = new ArrayList<>(arrTestA);
common.retainAll(arrTestB);
List<Integer> diff = new ArrayList<>();
for(Integer element : arrTestA)
if(!common.contains(element))
diff.add(element);
[here you print out elements of diff as The elements of A which is not in B]
ETA: Non Collection attempt:
int[] arr1 = { 1, 11, 5, 9, 4, 3, 4, 8 };
int[] arr2 = { 1, 7, 5, 3, 4, 8 };
Arrays.sort(arr1);
Arrays.sort(arr2);
for (int i : arr1) {
boolean contains = false;
for (int j : arr2) {
if (i == j) {
contains = true;
break;
}
}
if (!contains)
System.out.println("Arr2 doesn't contain number: " + i);
}
...or the loop can look like this:
outer: for (int i : arr1) {
for (int j : arr2) {
if (i == j) {
continue outer;
}
}
System.out.println("Arr2 doesn't contain number: " + i);
}
This is only one way method, but hope you see the point.
ETA2:
In my approach, in fact, these Arrays don't have to be sorted. You can simply delete lines of code that are responsible for sorting.
You can use a Set (it requires additional space to store its elements, but the code is simple):
Integer[] a = {0, 1, 2};
Integer[] b = {1, 2, 3};
Set<Integer> setFromA = new HashSet<>(Arrays.asList(a));
for (int num : b) {
if (!setFromA.contains(num)) {
System.out.println(num);
}
}
The same using Java 8 Stream API:
Arrays.stream(b).filter(num -> !setFromA.contains(num)).forEach(System.out::println);
Also, you can save result into a new list (if you wish):
List<Integer> result = Arrays.stream(b)
.filter(num -> !setFromA.contains(num))
.collect(Collectors.toList());
The idea is to sort the two arrays and go through both of them. By sorting them you would not have to cross-check all elements
int[] arr1 = {1,3,5,6,7,4,8};
int[] arr2 = {1,2,5,6,9,4,8};
Arrays.sort(arr1);
Arrays.sort(arr2);
int j =0;
for(int i = 0; i < arr1.length; i++){
while(j < arr2.length && arr2[j] < arr1[i]){
System.out.println("number: " +arr2[j]);
j++;
}
if(arr2[j] != arr1[i]){
System.out.println("number: " +arr1[i]);
}else{
j++;
}
}
I would not suggest using list here because contains takes o(n) time complexity.
Use set as its contains take constant time:(In case you want to maintain order also, go for LinkedHashSet)
// store array b into a set
Set<Integer> setInts = new HashSet<>(Arrays.asList(B);
// traverse array a, and check if set contains currrent element
for(int e : A)
{
if(!setInts.contains(e))
System.out.println(e);
}
Okay, so i need to find all the negative numbers of array and return them.I found the negative number, but how do i return them all? P.S yes i am a beginner.
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
System.out.println(findNumber(array));
}
public static int findNumber(int[] sum) {
int num = 0;
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < num) {
num = sum[i];
}
}
return num;
}
Java 8 based solution. You can use stream to filter out numbers greater than or equal to zero
public static int[] findNumber(int[] sum)
{
return Arrays.stream(sum).filter(i -> i < 0).toArray();
}
There are multiple ways of doing this, if you just want to output all of the negative numbers easily you could do this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
ArrayList<Integer> negativeNumbers = findNumber(sum);
for(Integer negNum : negativeNumbers) {
System.out.println(negNum);
}
}
public static ArrayList<Integer> findNumber(int[] sum) {
ArrayList<Integer> negativeNumbers = new ArrayList<>();
for (int i = 0; i < sum.length ; i++) {
if(sum[i] < 0) {
negativeNumber.add(sum[i]);
}
}
return negativeNumbers;
}
As you told you are beginner, i'm giving code in using arrays only.
Whenever you come across a negative number, just add it to the array and increment it's index number and after checking all the numbers, return the array and print it.
public static void main(String[] args)
{
int [] array = {5,-1,6,3,-20,10,20,-5,2};
int[] neg = findNumber(array);
for(int i = 0 ; i<neg.length; i++)
{
System.out.println(neg[i]);
}
}
public static int[] findNumber(int[] a)
{
int j=0;
int[] n = new int[a.length];
for(int i = 0; i<a.length ; i++)
{
if(a[i] <0)
{
n[j] = a[i];
j++;
}
}
int[] neg = new int[j];
for( int k = 0 ; k < j ; k++)
{
neg[k] = n[k];
}
return neg;
}
I hope it helps.
You can modify your method to iterate through the array of numbers, and add every negative number you encounter, to a List.
public static List<Integers> findNegativeNumbers(int[] num) {
List<Integers> negativeNumbers = new ArrayList<>();
for (int i = 0; i < num.length; i++) {
if(num[i] < 0) {
negativeNumbers.add(num[i]);
}
}
return negativeNumbers;
}
You could then print out the list of negative numbers from this method itself, or return the list with return to be printed in main.
You code is returning the sum of elements, but I understood that you wanted every negative number.
So, I assumed you want something like this:
public static void main(String[] args) {
int [] array = {5,-1,6,3,-20,10,20,-5,2};
Integer [] result = findNumbers( array );
for( int i : result )
{
System.out.println( i );
}
}
public static Integer[] findNumbers(int[] v) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < v.length ; i++) {
if(v[i] < 0) {
list.add(v[i]);
}
}
return list.toArray( new Integer[0] );
}
Is it?
Best regards.
public static int[] findNum(int[] array)
{
int negativeIntCount = 0;
int[] negativeNumbers = new int[array.length];
for(int i = 0; i < array.length; i++)
{
if(array[i] < 0)
{
negativeIntCount++;
negativeNumbers[i] = array[i];
}
}
System.out.println("Total negative numbers in given arrays is " + negativeIntCount);
return negativeNumbers;
}
To display as an array in output :
System.out.println(Arrays.toString(findNum(array)));
To display output as space gaped integers :
for(int x : findNum(array))
{
System.out.print(" " + x)
}
This question already has answers here:
Getting permutations of an int[] removing duplicates sets
(5 answers)
Closed 7 years ago.
I've just written a code for printing all the possible permutations from 1 to n in an int array in Java, but I think it is more complex than it needs to be. I am using Hashset to avoid repetitions. If someone finds something than can be simplified, please write.
import java.util.*;
public class ProblemFour {
private static int n;
private static void printResult(int[] result) {
Set<Integer> set = new HashSet<>();
Integer[] nums = new Integer[result.length];
for (int i = 1; i <= n; i++) {
nums[i - 1] = result[i - 1];
}
for (Integer num : nums) {
set.add(num);
}
if(set.size() == n) {
String s = "[ ";
for (Integer num : nums) {
s += num + " ";
}
System.out.println(s + "] ");
}
}
private static void permute(int[] result, int index) {
if (index == result.length) {
printResult(result);
return;
}
for (int i = 1; i <= n; i++) {
result[index] = i;
permute(result, index+1);
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("From 1 to: ");
n = input.nextInt();
int[] result = new int[n];
permute(result, 0);
}
}
I made this permutations code way back it uses lists as a data structure in it.
public List<List<Integer>> permute(int[] numbers) {
// we use a list of lists rather than a list of arrays
// because lists support adding in the middle
// and track current length
List<List<Integer>> permutations = new ArrayList<List<Integer>>();
// Add an empty list so that the middle for loop runs
permutations.add(new ArrayList<Integer>());
for ( int i = 0; i < numbers.length; i++ ) {
// create a temporary container to hold the new permutations
// while we iterate over the old ones
List<List<Integer>> current = new ArrayList<List<Integer>>();
for ( List<Integer> permutation : permutations ) {
for ( int j = 0, n = permutation.size() + 1; j < n; j++ ) {
List<Integer> temp = new ArrayList<Integer>(permutation);
temp.add(j, numbers[i]);
current.add(temp);
}
}
permutations = new ArrayList<List<Integer>>(current);
}
return permutations;
}