This question already has answers here:
Find an array inside another larger array
(15 answers)
Closed 4 years ago.
I defined an array which contains random numbers.I get some numbers from the user and put them in other array.I want to check whether first array contains the second array in order.My code is not enough to check order.It is just checking contains or not.
EX:
arr1=[45, 21,1,19 ,8,90,21,2] ,arr2=[21,1,19]
result=TRUE
arr1=[45,21,1,19,8,90,21,2] ,arr2=[21,19] result=FALSE
public class Main {
private static int[] array1;
public static int[] list() {
array1 = new int[10];
for(int i=0;i<array1.length;i++)
{
array1[i] = randomFill();
}
return array1;
}
public static void print()
{
for(int n: array1)
{
System.out.println(n+" ");
}
}
public static int randomFill()
{
Random rand = new Random();
int randomNum = rand.nextInt(90)+10; //to generate two digits number which is between 10-99 to the array
return randomNum;
}
public static void main(String args[])
{
list();
print();
Scanner s=new Scanner(System.in);
System.out.println("How many numbers will you add? ");
int n=s.nextInt();
int array2[]=new int[n];
System.out.println("Enter the numbers:");
for(int i=0;i<n;i++){//for reading array
array2[i]=s.nextInt();
}
for(int i: array2){ //for printing array
System.out.println(i);
}
int result=0;
for(int i=0;i<array1.length;i++)
{
for(int j=0;j<array2.length;j++)
{
if(array1[i]==array2[j])
{
result=result+1;
}
}
}
if(result==n)
{
System.out.println("TRUE");
}
else
{
System.out.println("false");
}
}
}
Here is the hard way without any helper
Integer i,j,k;
Boolean found=false;
for(i=0;i<arr1.length;i++) {
// we look for the index of the first element of the second array in the original one
if(arr2[0] == arr1[i] ) {
found=true;
// after that we iterate in both arrays simultaneously
for(j=1, k=i+1; j<arr2.length; j++,k++) {
// if we complete the iteration of the original array
// or if we find any two elements not equal we break
// we set then the boolean variable to false
if( k>=arr1.length || arr2[j] != arr1[k] ) {
found=false;
break;
}
}
if(found) break;
}
}
System.out.println(found);
Related
So I am trying to create a more time efficient stack implementation in java but I don't know how to make it work faster. Here is my code:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int[] n = new int[0];
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
n = push(x, n);
System.out.println("ok");
break;
case "pop":
n = pop(n);
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(n.length);
break;
case "back":
back(n);
break;
case "clear":
n = clear();
System.out.println("ok");
break;
}
}
}
static int[] push(int n, int[] x) {
int[] z = new int[x.length + 1];
for (int i = 0; i < x.length; i++){
z[i] = x[i];
}
z[x.length] = n;
return z;
}
static int[] pop(int[] x){
int z[] = new int[x.length-1];
for(int i = 0; i < z.length; i++){
z[i] = x[i];
}
System.out.println(x[x.length-1]);
return z;
}
static void back(int[] x){
System.out.println(x[x.length-1]);
}
static int[] clear(){
int x[] = new int[0];
return x;
}
}
Brief explanation:
Program takes values from scanner. And depending on a word that was entered, program proceeds with the corresponding instructions like push, pop, back... And it prints out the expected values to console with ok. Everything so far works properly as expected except the performance.
As you can see, in methods push and pop, my program creates new arrays and copies the values of the taken array which is x and adds 1 index with a pushed value or removes the popped value. This approach seems rather slow and inefficient. I couldn't find a more efficient way of doing that without picking arraylist or other classes from java library. But I have to use default integer arrays. And are there any other issues worsening the perfomance of the program?
How can I make my program work faster?
You can create member variables outside your method to keep track of the array and what is the size of it (similar to how array lists are implemented), no need to recopy the whole array everytime you need to pop/push.
You will need 2 variables, the array itself and the size (which will expand/shrink based on what you do)
You're better off creating a new class, I am gonna name it CustomStack
public class CustomStack
{
private int[] elements = new int[10]; // instantiated with a size of 10
private int size; // To track how many ints we currently have
....
}
You can now access the array and the size within the methods.
So first you need the push method, but wait there is a trick here, what if I already reached the max size of the array? (i.e: 10 numbers are already inside the array), well you need to cater for this, a known way to tackle this is create a new array with double the size of the current array and then copy all the values to the new array.
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2]; //double the size
System.arraycopy(elements, 0, temp, 0, elements.length); // copy the array
elements = temp; //set our member variable array to the new array
}
}
And the push method:
public void push(int n)
{
validateArraySize(); // The previos method to check if we can safely insert the value
elements[size] = n;
size++;
}
Regarding the pop method, it is very straight forward, you just need to check if there are any integers inside the array:
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1]; //Get the last value
elements[size - 1] = 0; // remove the last value
size--;
}
return valueRemoved; // return removed value
}
The whole class will look like this:
public class CustomStack
{
private int[] elements = new int[10];
private int size;
public void push(int n)
{
validateArraySize();
elements[size] = n;
size++;
}
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
}
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1];
elements[size - 1] = 0;
size--;
}
return valueRemoved;
}
public int getSize()
{
return size;
}
public void back()
{
if (size == 0)
System.out.println("No elements found");
else
System.out.println(elements[size - 1]);
}
public void clear()
{
elements = new int[10];
}
}
Your main method will become:
public static void main(String[] args) {
CustomStack customStack = new CustomStack();
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
customStack.push(x);
System.out.println("ok");
break;
case "pop":
int val = customStack.pop();
System.out.println(val + " is popped");
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(customStack.getSize());
break;
case "back":
customStack.back();
break;
case "clear":
customStack.clear();
System.out.println("ok");
break;
}
}
I'm traying to create x amount of arrays, each one called square(number)=new Array....
int numberofsquares=1;
int prgrm=0;
int amount=0;
int v=1;
while(prgrm==0) {
System.out.println("Enter another square? (y/n)");
if (stdin.next().startsWith("y")) {
List<String> square(x) = new ArrayList<String>();
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("1,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("2,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
while(amount!=3)
{
System.out.println("Enter: ");
square(x).add("3,"+v+","+stdin.next());
v++;
amount++;
System.out.println(firstsquare);
}
amount=0;
v=1;
} else {
prgrm++;
}
}
if (prgrm==1) {
System.out.println("Finish");
}
So the first time you press y the array that creates is called square1, the next one square2,squre3...
How can I do this? Thanks :D
No, You can't create variable names dynamically.
But if your intention is to create different storage space then you can use List<List<String>>(as mentioned already) and can access each element using get() method.
Following is an working example. See it working here:
public static void main (String[] args) throws java.lang.Exception
{
try(Scanner stdin = new Scanner(System.in))
{
int numberofsquares=1;
int prgrm=0;
int v=1;
List<List<String>> square = new ArrayList<>();
while(prgrm==0)
{
System.out.println("Enter another square? (y/n)");
if (stdin.next().startsWith("y"))
{
for(int i=0; i<3; i++)
{
square.add(new ArrayList<String>());
//Get last element's index
int lastIndex = square.size()-1;
//Get last element and add a String
square.get(lastIndex).add((i+1) +","+v+","+stdin.next());
v++;
}
}
else
{
prgrm++;
}
}
if (prgrm==1)
{
System.out.println("Finish");
}
System.out.println("Lists are: " + square);
}
}
Use nested lists, eg:
List<List<String>> squares = new ArrayList<>();
After trying out a few ways to fix my code from an arrayindexoutofbound exception, there's one way it wouldn't produce the exception, however the program would not output anything like it should, it would not throw exceptions or errors, and it shows that the program is not terminated. Here's the code:
import java.util.*;
public class treez {
final Scanner in;
public treez()
{
in=new Scanner(System.in);
run();
in.close();
}
public void run()
{
System.out.println("Enter normal restaurant numbers and pho restaurant numbers");
final String input=in.nextLine();
final int[] rest=createarray(input);
final int normal=rest[0];
final int pho=rest[1];
final String input1=in.nextLine();
final int[] phoresspecific=createarray(input1);
Arrays.sort(phoresspecific);
boolean[][] matrix;
matrix=new boolean[normal][normal];
for(int i=0;i<normal;i++)
{
for(int j=0;j<normal;j++)
{
matrix[i][j]=false;
}
}
int[] total=new int[normal];
for(int i=0;i<matrix.length;i++) matrix[i]=new boolean[normal];
for(int i=0;i<normal;i++)
{
total[i]=i;
total[i]=Arrays.binarySearch(total, i);
}
Arrays.sort(total);
for(int i=0 ; i < normal - 1; i++) {
int x = 0;
int y = 0;
String ans = in.nextLine();
int[] arraya = createaarray(ans);
x = arraya[0];
y = arraya[1];
matrix[x][y]= true;
matrix[y][x]=true;
}
in.close();
int answer=decisions(pho,matrix,phoresspecific,normal);
System.out.println(answer);
}
private int decisions(int pho, boolean matrix[][],int[] phoresspecific,int normal)
{
int steps=0;
if(pho==2)
{
for(int j=0;j<normal-1;j++)
{
for(int i=phoresspecific[0];i<normal-1;i++)
{
if(matrix[j][i]==true)
{
j++;
steps++;
if(j==phoresspecific[1]) break;
}
}
if(j==phoresspecific[1]) break;
}
}
else
{
int counter=0;
int[] step=new int[pho-1];
for(int j=0;j<pho-1;j++)
{
counter=0;
for(int i=0;i<normal-1;i++)
{
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
{
i++;
step[j]++;
if(i==j)
{
counter++;
}
}
}
if(counter==pho) break;
}
}
Arrays.sort(step);
steps=step[0];
}
steps--;
return(steps);
}
private int[] createarray(final String input)
{
final String[] args=input.trim().split("\\s+");
final int[] list=new int[2];
for(int i=0;i<2;i++)
list[i]=Integer.parseInt(args[i]);
return list;
}
private int[] createaarray(final String ans)
{
final String[] args=ans.trim().split("\\s+");
final int[] list=new int[2];
for(int i=0;i<2;i++)
list[i]=Integer.parseInt(args[i]);
return list;
}
public static void main(String args[])
{
new treez();
}
}
From the previous mistakes, I believe the error is either in line 83 or 85, which are:
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
in
for(int l=phoresspecific[j];l<normal-1;l+=0)
{
if(matrix[i][l]==true)
{
i++;
step[j]++;
if(i==j)
{
counter++;
}
}
}
With input:
8 5
0 6 4 3 7
0 1
0 2
2 3
4 3
6 1
1 5
7 3
The program would neither produce an output or terminate. Help would be appreciated.
Edit:the exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at treez.decisions(treez.java:85)
at treez.run(treez.java:52)
at treez.<init>(treez.java:9)
at treez.main(treez.java:127)
Edit2:This program is used to determine the minimum time used for a person to reach all the locations wrote in from input line 2. There's no edge weight since it takes one minute from one place to another. All the lines after second lines states there is a road connecting place a and b.
Have you checkt your build configurations?
And its kind a hard looking for possible errors when you provide not a lot of information about your program.
EDIT: I managed to get it running and can confirm that you program (with your input does not return anything and I didn't step trough every piece of code)
But you always use the "createarray" function, which you have two times implemented and its the same function (exept of the name of the value you pass).
Then you have an infinite loop in this code:
for(int i=0;i<normal-1;i++){
for(int l=phoresspecific[j];l<normal-1;l+=0){
if(matrix[i][l]==true){
i++;
step[j]++;
if(i==j) counter++;
}
}
if(counter==pho) break;
}
The inner for-loop doesnt increment its value and is always trying to evaluate the if condition wich will always stay the same due to the never changing index l . That is probably your error.
Another EDIT:
In the second line of your parameters you have more than two values, but your functions always read only two parameters.
I need to create a JAVA method: public static int[] Numb() that reads and returns a series of positive integer values. If the user enters -1 we should stop accepting values, and then I want to call it in the main method. And we should return to the user integers that he entered them, with the total number.
So if he entered the following:
5 6 1 2 3 -1
So the total number is : 6
The numbers entered are: 5 6 1 2 3 -1
I tried the following:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
}
public static int[] readNumbers(int[] n)
{
int[] a = new int[n.length];
Scanner scan = new Scanner(System.in);
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.nextString();
}
}
}
And here is a fiddle of them. I have an error that said:
Main.java:21: error: cannot find symbol
a[i] = Integer.nextString();
I am solving this exercise step by step, and I am creating the method that reads integers. Any help is appreciated.
Integer.nextString() doesn't exist, to get the next entered integer value, you may change your loop to either :
for(int i = 0;i<n.length;i++) {
a[i] = scan.nextInt();
}
or as #vikingsteve suggested :
for(int i = 0;i<n.length;i++) {
String token = scan.next();
a[i] = Integer.parseInt(token);
}
public static void main(String[] args) {
List<Integer> numList = new ArrayList<>();
initializeList(numList);
System.out.println("Num of integer in list: "+numList.size());
}
public static void initializeList(List<Integer> numList) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while(flag) {
int num = sc.nextInt();
if(num==-1) {
flag = false;
}else {
numList.add(num);
}
}
sc.close();
}
Since the number of integers is unknown, use ArrayList. It's size can be altered unlike arrays.
You can create something like arraylist on your own..it can be done like this:
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
CustomArray c = new CustomArray(3);
boolean flag = true;
while (flag) {
int num = sc.nextInt();
if (num == -1) {
flag = false;
} else {
c.insert(num);
}
System.out.println(Arrays.toString(c.numList));
}
sc.close();
}
}
class CustomArray {
int[] numList;
int size; // size of numList[]
int numOfElements; // integers present in numList[]
public CustomArray(int size) {
// TODO Auto-generated constructor stub
numList = new int[size];
this.size = size;
numOfElements = 0;
}
void insert(int num) {
if (numOfElements < size) {
numList[numOfElements++] = num;
} else {
// list is full
size = size * 2; //double the size, you can use some other factor as well
//create a new list with new size
int[] newList = new int[size];
for (int i = 0; i < numOfElements; i++) {
//copy all the elements in new list
newList[i] = numList[i];
}
numList = newList;//make numList equal to new list
numList[numOfElements++] = num;
}
}
}
import java.util.Random;
public class Mutation {
public Mutation()
{
}
private ArrayList<int[][]> allWords=new ArrayList<int[][]>();
public ArrayList<int[][]> wordGenrator(int noOfWords)
{
int rand,j;
int word[][]=new int[8][8];
for(int i=0;i<noOfWords;i++)
{
for(j=0;j<8;j++)
{
rand = new Random().nextInt(2);
System.out.print(rand);
word[i][j]=rand;
}
System.out.print("\n");
allWords.add(word);
}
return allWords;
}
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++)
{
counter=0;
for(int j=0;j<8;j++)
{
if(equals(this.allWords.get(i)[i][j]==1)
{
counter++;
}
}
if(counter==8)
{
return true;
}
}
return false;
}
The loop is running well, but this is not comparing correctly. I want to do if allword(i) have all 1's then return true otherwise false.
Now this is my whole code of same class.. I'm calling these functions in another main class...
As far as I read your code and your text I think you have a int[5][8] Array and you'd like to check whether there is at least one "1" in every row of the array or not. In that case you juse need to change the the Code as followed
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++)
{
counter=0;
for(int j=0;j<8;j++)
{
if(this.allWords.get(i)[i][j]==1)
{
counter++;
}
}
if(counter < 1) // If there were no 1's then count should still be 0
{ // and the method returns false as a row was found
return false; // in which there wasn't a 1
}
}
return true;
}
That ; should be a )
if(equals(this.allWords.get(i)[i][j]==1);
Also, the == is already comparing two things, thus the "equals" is not. Get rid of the equals.
This should be outside the for:
allWords.add(word);
With that change, there will only be one word[][], thus, change the i for a 1:
this.allWords.get(1)...
The problem is with 2D array initialization
What will be value of 2D array if noOfWords=1?
int word[][]=new int[8][8];
for(int i=0;i<noOfWords;i++)
{
for(j=0;j<8;j++)
{
rand = new Random().nextInt(2);
System.out.print(rand);
word[i][j]=rand;
}
System.out.print("\n");
allWords.add(word);
}
Look at the inline comments.
public boolean isExistWordOfAllOnes()
{
int counter;
for(int i=0;i<5;i++) // iterate all the words that are 2D arrays
{
counter=0;
for(int j=0;j<8;j++) // row
{
for (int k = 0; k < 8; k++) { // column
if (this.allWords.get(i)[j][k]==1) { // if it is equal to 1
counter++;
}
}
}
if(counter==8*8)//total 64 ones in 8*8 2D array
{
return true;
}
}
return false;
}