Checking value of an index in an If statement Ruby - arrays

Very new to Ruby and I am using an If statement to see if the value of an index is equal to an specific integer. I am given a string "12345" and want to see if the first char is equal to 1 so then I can delete it and post the array as a string again.
I convert the string to an array then check the value of the index[0]. I feel I am missing something very simple. Can anyone help?
def number
num = ("12345")
numArr = num.split("")
if numArr.values_at(0) == 1
numArr.shift
numArr.join("")
end
end

you can just do this
a.slice(1, a.length) if a[0] == "1"
your code would work too if you add quotes around 1 in your if condition

You can just work with the string directly no need to use split:
num = ("12345")
if num[0] == '1'
num.slice!(0)
end
puts num
Output:
"2345"

Related

how to replace null with 0 in scala array

I am a scala beginner and I face a problem when I am doing my homework because there is null in the text file for example (AFG,Asia,Afghanistan,2020-02-24,1.0,1.0,,,,,0.026,0.026). So, I need to replace the null in array with zero. I read the scala array members and try the update and filter method but I cannot solve it. Can someone help me?
val filename = "relevant.txt" //Access File
val rf = Source.fromFile(filename).getLines.toArray //Read File as Array
for(line <- rf){ //for loop
line.(**How to replace the null with 0?**)
//println(line.split(",")(0))
if (line.split(",")(0).trim().equalsIgnoreCase(iso_code)){ //check for correct ISO CODE , ignores the casing of the input
total_deaths += line.split(",")(4).trim().toDouble //increases based on the respective array position
sum_of_new_deaths += line.split(",")(5).trim().toDouble
record_count += 1 //increment for each entry
}
}
val cells = line.split(",")
.map(_.trim)
.map(it => if (it.isEmpty) "0" else it)
Then you can use it like total_deaths += cells(4).toDouble
BTW, null usually refers to "null pointer" in scala.
In your case, you don't have any "null pointer", you just have "empty string"
What you may do is something like this:
for (line <- rf) {
val data = line.split(',').toList.map(str => Option(str).filter(_.nonEmpty))
}
That way data would be a List[Option[String]] where empty values will be None, then you may use pattern matching to extra the data you want.
if you had to apply the change where you want:
//line.(**How to replace the null with 0?**)
you could do:
val line2 = if (line.trim().isEmpty) "," else line
then use line2 everywhere else.
As a side thing, if you want to do something more scala, replace .toArray with .toList and have a look at how map, filter, sum etc work.

Preallocating array for string concatenation

Say I have an array x of integers (0 or 1) and that I want to build a string s such that I append A if x(i)=0 and B if x(i)=1, as I loop over x. For example I could do
s = '';
for i = 1:length(x)
if x(i) == 0
s = [s 'A'];
elseif x(i) == 1
s = [s 'B'];
end
end
While this works, MATLAB complains about the array not being preallocated. How could I do this? I cannot for example do
s = zeros(1,length(x))
because then s is treated as a numeric array, and if, for example, I do s(i)='A', I just assign to s(i) the char calue of 'A'.
Any help would be greatly appreciated!
There are special functions to prealocate zeros ones or similar, but you can preallocate whatever type you want using repmat
s=repmat('_',size(x))
Besides this, you don't need a loop at all to achieve this. The simple solution:
s=repmat('_',size(x));
s(x==0)='A';
s(x==1)='B';
As you already noticed the conversion between numbers and chars, there is also a 1-line implementation.
s=char(x+'A')

Function to encoding input characters in MATLAB

I want to create a function that encrypts the input sentence. This encryption will replace the first letter of each word with the next letter in the ASCII table, and the second letter with the next, ....
So basically, the resulting output for abc def should be bcd efg. However, when I run my function, the space will also be replaced, i.e. output will be bcd!efg. Why is this so? Thanks.
Below is what I have written:
function out = encrypt(input)
ascii_encode=double(input);
line={ascii_encode};
counter=0;
for a=1:length(line)
if line{a}==32
counter=0;
else
counter=counter+1;
line{a}=line{a}+counter;
end
line{a}=char(line{a});
end
out=line;
end
You should be careful handling cells.
Try line{a} , line(a) , line(1){a}, to understand how they work.
The code should be like this,
function out = encrypt(input)
ascii_encode = double(input);
line = {ascii_encode};
for a = 1 : length(line{1})
if line{1}(a) == 32
continue;
end
line{1}(a) = line{1}(a) + 1;
end
line{1} = char(line{1});
out = line{1};
end
And there is no need for counter, you just have to jump when if is true.
Kamtal's answer is perfectly right. You assign your input to a cell and then you were not accessing an index in the cell value (which is still a char array), but the full cell value.
Follow Kamtal answer if you still want to use cells type, and look at the cell documentation.
Note that you could also benefit by Matlab vectorization capabilities, and simplify your function by:
function out = encrypt(input)
charToKeep = ( input==' ' ) ; %// save position of character to keep
out = char(input+1) ; %// apply the modification on the full string
out(charToKeep) = ' ' ; %// replace the character we saved in their initial position
end

Search for number in an array

I'm having some trouble with the exercise I got given from my teacher.
Exercise:
Write a program to input 5 numbers. Ask the user to a input a number for searching the array. The program should search for this number and tell the user if it has been found in the array or not. For example, if it has been found then the position of the array which the number occupies should be display. For example "Your number is 6. It has been fond in the position 3 of the list."
Obviously, I can just use a for loop and get 5 numbers and put them into the array. But Im not sure how to check if then the number the user wants to search for is in the array.
Heres my attempt http://pastebin.com/t2DcdSvU Im not sure how to put it into code tags :S
First, obtain you user input. So let's say you have your array, and a target value. For the example, let's just say your user input created the following:
Dim numbers = {1, 2, 9, 6, 4}
Dim target = 2
Now all you need to do is loop through the array, and compare the target, to the current value of the array.
For x = 0 To 4
If target = numbers(x) Then
MsgBox "Your number is " + target ", found at position " + x
Exit For
End If
Next x
You can use that same concept to search the array.
Assuming you won't have a sorted array, you can simply use a for loop to check each value of the array and compare with the entered value to search.
Use a for loop or whatever construct you want to populate the array, then use another to loop through the array and for each value, do a compare and determine if the user entered a number that's in the array.
If you get a match, print out the resulting index number and return.
Here's a sample of code that will do what you need:
Dim value As Integer
value = 0
' This loop goes from 0 to 4.
For index As Integer = 0 To 4
value = myArray(index)
' Exit condition if the value is the user number.
If (value = usernum) Then
Console.writeline("Your number was " & usernum & " found at: " & index & "\n")
Exit For
End If
Next

VBScipt Array Comparison

i have a problem with VBScript.
I am trying to loop through an array to compare all the values match.
I.e i have a tring array like the one below. i want to compare each of the values match using vbscript.
tmp(0) = "12345"
tmp(1) = "12345"
tmp(2) = "12345"
tmp(3) = "12345"
tmp(4) = "12345"
If i loop over the array i will have to do this twice in order to compare the vals. But how can i handle the first values. If the first value is wrong then its never picked up as both arrays are identical. I do not know how to get around this problem. Could someone please advise.
for x=0 to UBound(tmp)
for each val in tmp
if ( tmp(x) <> val)
print (mismatch)
End if
Next
Next
Not sure if I understand your question correctly. Do you want to check if all values of an array are equal? If so, something like this should do:
elementsEqual = True
For i = 1 To UBound(tmp)
If tmp(i) <> tmp(0) Then
elementsEqual = False
Exit For
End If
Next
You don't need to compare each element with each other element to check if all are equal. If not all elements are equal, then one of them will be inequal to the first element, so you just need a single loop.

Resources