Here is a java snippet that I worked on before for a 2D array that uses a linear search to find the index of a specific number
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int arr[][] = { { 0, 2, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 1, 1, 3 },
{ 0, 1, 1, 1, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0 } };
int target = 2;
int ans[] = linearSearch(arr, target);
System.out.println("Element found at index: "
+ Arrays.toString(ans));
}
public static int[] linearSearch(int[][] arr, int target) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (arr[i][j] == target) {
return new int[] { i, j };
}
}
}
return new int[] { -1, -1 };
}
}
list = [1,2,3,4,5,6,8,9,10,99999]
# print the first index(zero based counting)
print(list[1])
# add 11 to the end of the list
list.append(11)
print(list)
# insert a number into a certain index of the list
list.insert(6, 7)
print(list)
# remove a number from the list
list.remove(99999)
print(list)
2
[1, 2, 3, 4, 5, 6, 8, 9, 10, 99999, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99999, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
list = [2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10]
# create a new list so that the for loop can append the non duplicates here
list_duplicates = []
# for loop for every number in list
for item in list:
# since nothing in the empty list, add the number from the duplicate list to the empty list
# it wont add the same number because once it adds the first number it will not satisfy the condition
if item not in list_duplicates:
list_duplicates.append(item)
print(list_duplicates)
[2, 3, 4, 5, 6, 7, 8, 9, 10]
import math
# function for calculating the worst case iteration that takes array_length as a parameter
def worst_case_iterations(array_length):
# whatever the array length is, find log 2 of it and round up
return math.ceil(math.log2(array_length))
# defines the array_length variable we want to find
array_length = 20
worst_case_iterations_count = worst_case_iterations(array_length)
print(worst_case_iterations_count)
5
3) You have a list myList
containing the following elements: [10, 20, 30, 40, 50].
FOR i FROM 0 TO LENGTH(myList) {
x <- myList[i]
myList[i] <- x * 2
}
What will be the final content of myList
after executing this algorithm?
A) [20, 40, 60, 80, 100]
B) [10, 20, 30, 40, 50]
C) [10, 40, 30, 20, 50]
D) [50, 40, 30, 20, 10]
submit on utterance
The correct answer is A because the for loop goes through all the items in the list and multiples each item by 2.
##