Find the first "1" in zero array - arrays

I have an array "0000011111"
I need to find the first occurrence of "1".
How can I do that in efficient way ?
my solution is: (I think there is a better way)
$array = array(0,0,1,1,1);
for($i=0;$i<count($array);$i++)
{
if($array[$i] == 1)
{
var_dump($i);
return;
}
}

Your solution is already as efficient as possible, but there's a built-in method in PHP that will do this for you:
$array = array(0,0,1,1,1);
var_dump(array_search(1, $array)); // int(2)
Note that array_search will return the boolean FALSE in the case where there are no 1s in the array.
EDIT
I made the assumption that the original code is PHP just because it looked that way. :-)

Unfortunately, since there is no necessity for any of the numbers to be "1" and since you are only going through the array once, this is the most efficient solution. Binary search or any such algorithm wont work as this array is quite obviously not sorted.
Sample inputs:
0101101
1000101
In either case, binary search would not work.

If you can somehow convert the array efficiently to a number, It is possible to find the first 1 efficiently with log base 2.
var number = 0b010000010;
console.log(Math.floor(Math.log2(number)))
EDIT The main reason for doing this is because there are hardware instructions for doing log base 2 that make it constant time.
Of course if you cannot store your array as a binary string, because it is too long or something like that, this solution is not for you.

Related

Sum of elements of two integer array in a single string array in Swift

Have a function Arr(strArr) read the array of strings stored in strArr which will contain only two elements, both of which will represent an array of positive integers. For example of strArr is ["[1, 2, 5, 6]", "[5, 2, 8, 11]"], and goal for this is to add the elements in corresponding locations from both arrays. For the example input, the program should do the following additions: [(1 + 5), (2 + 2), (5 + 8), (6 + 11)] which then equals [6, 4, 13, 17]. Return this resulting array in a string format with each element separated by a hyphen: 6-4-13-17.
If the two arrays do not have the same amount of elements, then simply append the remaining elements onto the new array.
Examples
Input: ["[5, 2, 3]", "[2, 2, 3, 10, 6]"]
Output: 7-4-6-10-6
Input: ["[1, 2, 1]", "[2, 1, 5, 2]"]
Output: 3-3-6-2
Thank you for your help.
The question seems obviously a homework exercise, and as was pointed out in comments that's not what StackOverflow is for; however, I know a lot of students who struggle to know even how to approach a problem. I think helping with that is a good thing, so I won't give a solution to the problem, but rather advice about approaching it.
The general formula that works for most problems is simple: Break the problem into smaller sub-problems, and solve each of those independently, then combine the sub-solutions. If any of those sub-problems are too complicated, repeat the process for those, and so on.
Homework problems, and a lot of real world problems, usually break down into three main sub-problems:
Transform some input into a more conveniently computable form.
Process the transformed input into some computed outputs.
Transform the computed outputs into a specified format.
Applied to your problem, you have:
How to parse a specially formatted string into an array of integers.
How to sum corresponding elements of two arrays, taking into account they may be of different lengths, to produce an array of sums.
How to transform an array of integers into a specially delimited string output.
The solution to your top-level problem will involve applying the sub-solutions in that order, but you don't have to solve them in that order. If you're having difficulty with getting started with the first one, solve one of the easier sub-solutions first to get some momentum. Psychology is actually quite important in problem solving. Believing you can solve it is half of actually solving it, so solve the easier problems first to get that factor working in your favor.
Maybe you regard the sub-problem 3 as the easiest to solve: So write a function place-holder for it (aka, a "stub function"), and make up some input data to test it. This would lead you to write something like this:
func formatOutput(from intArray: [Int]) -> String
{
// Your implementation will go here
}
let actual = formatOutput(from: [1, 2, 3, 4])
let expected = "1-2-3-4"
// If you're doing this in a playground, app, or command line tool
if actual != expected {
fatalError("FAILED: \"\(actual)\" != \"\(expected)\"")
}
else { print("Yay! Passed!") }
// If you're using XCTest
XCTAssertEqual(actual, expected)
That won't even compile yet, because formatOutput has to return something, and it doesn't yet. The key thing is that you've written your usage code first, and expressed in code what you expect. Now focus on the guts of formatOutput. If you want to take a Test Driven Development approach (TDD), maybe at first just return an empty string from formatOutput so you can be sure the code compiles and you see a failing test. Then implement it correctly if you know how, or in small steps if you're not clear on what to do. As you get the exact thing you're testing for working, you can keep adding more tests and improving formatOutput until you've verifiably got it doing everything it's supposed to do. Remember the KISS principle: "Keep It Simple, Stupid!" Don't over-think the solution, and save doing it "cleverly" for another day, which often never comes because the simple thing was sufficient.
At that point you have one of the sub-problems solved, so you move on to the next, following the same pattern. And the next, until all the parts are solved. Then put them together.
You'll note that sub-problem 2 has a bit of an extended description, especially the part specifying that the arrays may be of different lengths. Unless you already know how to solve that problem as stated, that sort of thing indicates it's a good candidate to be broken into yet simpler problems:
2a. How to sum corresponding elements of two arrays of the same length.
2b. How to modify 2a to handle arrays of different lengths.
2b can be done a few different ways:
2.b.1. Apply 2.a to sub-arrays of common length, then handle the remaining part of the longer one separately
OR
2.b.2. Enlarge the shorter array so that it is the same length as the longer one, so 2.a can be applied unmodified.
OR
2.b.3. Modify 2.a so that it can treat the shorter array as though it were the same length as the longer one, without actually copying or adding new elements.
OR
2.b.4. Modify 2.a so that it doesn't have to do anything special for different lengths at all. Hint: think more about the output and its length than the inputs.
When faced with alternatives like that, in the absence of any external constraints that would make one option preferred over the others, pick the one that seems simplest to you (or the most interesting, or the one you think you'd learn the most from). Or if you have time, and want to get the most out of the exercise, implement all of them so you can learn how they are all done, and then pick the one you like best for your final code.
func getResult(strArr: [String]) -> String {
let intArray1 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[0].utf8))) ?? []
let intArray2 = (try? JSONDecoder().decode([Int].self, from: Data(strArr[1].utf8))) ?? []
var arrayResult = zip(intArray1,intArray2).map(+)
let commonCount = arrayResult.count
arrayResult.append(contentsOf: intArray1.dropFirst(commonCount))
arrayResult.append(contentsOf: intArray2.dropFirst(commonCount))
return arrayResult.map(String.init).joined(separator: "-")
}
let result1 = getResult(strArr : ["[5, 2, 3]", "[2, 2, 3, 10, 6]"])
let result2 = getResult(strArr : ["[1, 2, 1]", "[2, 1, 5, 2]"])
You can use this function to get your desired result.

How does Ruby's Combined Comparison Operator work?

First question on stackoverflow :)
I'm going through the Ruby course on Codecademy and I'm stuck on something.
fruits = ["orange", "apple", "banana", "pear", "grapes"]
fruits.sort! {|first, second| second <=> first}
print fruits
I don't know how to phrase this question. On Codecademy the assignment was to set up the array to be displayed in reverse on the console. After some research, I was able to figure it out. I understand how it works and the order to put it in the code not why. I'm aware that "<=>" compares two objects, but how do the items within the array become objects when we don't declare them as such?
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
First question: At various points in its operation the sort method has to compare pairs of objects to see what their relative ordering should be. It does the comparison by applying the block you pass to sort, i.e., {|first, second| second <=> first}. Not sure what you mean by "how do the items within the array become objects when we don't declare them as such?". All data in ruby is an object, so there's no declaration or conversion needed given that all variables are object references.
Second question: Yes, you could do fruits.sort.reverse, but that would require additional work after the sort to do the reverse operation. Also, reverse can't handle more complex sorting tasks, such as sorting people by multiple criteria such as gender & last name, or hair color, height, and weight. Writing your own comparator can handle quite complex orderings.
String literals can be used to create string objects in Ruby, there is no need to use the String class to create the object. The following two are equivalent:
"Hello, world!"
String.new("Hello, world!")
More information can be found here.
Secondly, what is the purpose of writing this code in this way when we could do fruits.sort.reverse?
Please contact Codecademy about this, but I suspect it's for learning more about how <=> works.

How to best modify an array using .each

I am using Ruby, and I am relearning arrays and trying to better understand them. I know what they are but have never fully utilized them. I have an array, odds, and wanted to double every number in it. I came up with the below solution; however, I wanted to see if there was a more elegant/simple solution to my problem.
odds = [1,3,5,7,9]
odds.each do |x|
odds[odds.index(x)]=x*2
end
end result is odds = [2,6,10,14,18]
You can use the map! enumerator to modify every item in an array:
odds.map!{ |x| x*2}
If you really want to modify in place, and you really want to use each, I guess your approach is as good as any. It doesn't feel idiomatic, but it does meet your stated constraints.
Here are some more common approaches:
Array.map
Mapping the array with map won't modify the original array (it's not in-place), which is often a good thing, but it might not be what you're looking for:
odds.map { |x| x*2 }
Array.map!
If you really do want to modify the original array, you can use map! to map in-place:
odds.map! { |x| x*2 }
Array.each_index
You did ask specifically about each, so if you want to use an each and you want to modify the original array, each_index might be your best bet:
odds.each_index { |i| odds[i] *= 2 }

How to optimize a list search in SML/NJ?

I am writing a piece of code in SML/NJ and need, at some point, to access a list, which I have already created. I know that, in C, for example, accessing an array takes constant time. So, I thought that that would be the case for ML as well. Apparently, however, the built-in List.nth(l,i) function has a complexity that is linear to the size of the list given as argument.
I then turned to arrays, but I think that the Array.sub function has, also, linear complexity.
So, given the fact the accesing a tuple, like #2(12,5.6,"foo"), has an O(1) complexity, I would like to ask whether there is a way, I could use a tuple, instead of a list,but access it dynamically.
For example, say I want to write a function that takes a tuple, with only boolean values, and an integer n, and returns True if the n-th element of the tuple is true.Something like:
fun isTrue (n,tup) =
if #n(tup) then true
else false;
I know this isn't valid SML, so is there a way to write such a function?
Thanks a lot in advance for your time!
The sml function has O(1) complexity, so feel free to use it!
e.x.
`fun isTrue (n,tup) =
if Array.sub(tup,n) then true
else false;`
As far as the tuple is concerned, you can only use a specific number, not a variable in a tuple.
e.x.
fun isTrue (n,tup) =
if #2 (tup) then true
else false;

Array.isDefinedAt for n-dimensional arrays in scala

Is there an elegant way to express
val a = Array.fill(2,10) {1}
def do_to_elt(i:Int,j:Int) {
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
}
in scala?
I recommend that you not use arrays of arrays for 2D arrays, for three main reasons. First, it allows inconsistency: not all columns (or rows, take your pick) need to be the same size. Second, it is inefficient--you have to follow two pointers instead of one. Third, very few library functions exist that work transparently and usefully on arrays of arrays as 2D arrays.
Given these things, you should either use a library that supports 2D arrays, like scalala, or you should write your own. If you do the latter, among other things, this problem magically goes away.
So in terms of elegance: no, there isn't a way. But beyond that, the path you're starting on contains lots of inelegance; you would probably do best to step off of it quickly.
You just need to check the array at index i with isDefinedAt if it exists:
def do_to_elt(i:Int, j:Int): Unit =
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j))
EDIT: Missed that part about the elegant solution as I focused on the error in the code before your edit.
Concerning elegance: no, per se there is no way to express it in a more elegant way. Some might tell you to use the pimp-my-library-Pattern to make it look more elegant but in fact it does not in this case.
If your only use case is to execute a function with an element of a multidimensional array when the indices are valid then this code does that and you should use it. You could generalize the method by changing the signature of to take the function to apply to the element and maybe a value if the indices are invalid like this:
def do_to_elt[A](i: Int, j: Int)(f: Int => A, g: => A = ()) =
if (a.isDefinedAt(i) && a(i).isDefinedAt(j)) f(a(i)(j)) else g
but I would not change anything beyond this. This also does not look more elegant but widens your use case.
(Also: If you are working with arrays you mostly do that for performance reasons and in that case it might even be better to not use isDefinedAt but perform validity checks based on the length of the arrays.)

Resources