I'm trying to get position value of a string. This works well by printing the integer value of each.
How do I get the sum of the alphabet index in the for loop?
val name = "abc".toLowerCase(Locale.ROOT)
for (element in name) {
val position = element - 'a' + 1
}
Have a variable that you can just add each index to.
val input = "abc".toLowerCase(Locale.ROOT)
val alphabet = "abcdefghijklmnopqrstuvwxyz"
var sum = 0
for (element in input) {
sum += alphabet.indexOf(element)
Log.d("TAG", "${alphabet.indexOf(element) + 1}")
}
Log.d("TAG", "${sum}")
You can achieve that in a really concise way with the sumBy function:
val input = "abc".toLowerCase(Locale.ROOT)
val alphabet = "abcdefghijklmnopqrstuvwxyz"
val sum = input.sumBy { element ->
Log.d("TAG", "${alphabet.indexOf(element) + 1}")
alphabet.indexOf(element)
}
Edit (after question changed):
val name = "abc".toLowerCase(Locale.ROOT)
val sum = name.sumBy { element ->
element - 'a' + 1
}
Try it out here
Related
I have an array with elements like a = [5,6,8,9,2,6,8]. So when I do the first iteration I skip the first index and then add the remaining elements in the array and if I do the second iteration I skip the second element and then add the remaining elements. ex: for the second iteration I skip the second element and then add the remaining elements as 5 + 8 + 9 + 2 + 6 + 8 = 38 like this I want to add the elements and find the highest sum of the elements and minimum sum of the elements. How to do that in swift?
Try this:
let array: [Int] = [1, 2, 3, 4, 5]
var min: Int!
var max: Int!
for (index, _) in array.enumerated() {
var auxArray = array
auxArray.remove(at: index)
let sum = auxArray.reduce(0, +)
if min == nil || max == nil {
min = sum
max = sum
} else if sum < min {
min = sum
} else if sum > max {
max = sum
}
}
print("MIN: \(min!), MAX: \(max!)")
You can do it with one iteration
let a = [5,6,8,9,2,6,8]
var sum = 0
var smallestNumber = a[0]
var largestNumber = a[0]
for number in a {
sum += number
if number < smallestNumber {
smallestNumber = number
}
if number > largestNumber {
largestNumber = number
}
}
let smallestSum = sum - largestNumber
let largestSum = sum - smallestNumber
If I have an array, for example this
Dim Players() As String = {"Adam", "Helen", "Jack", "Emily"}
How do I change the position of each element by a value, for example if by 1, Adam will move to 2, Helen will move to 3, and Emily should come back to 1.
I was able to do this if increment by 1. I would have the last element stored in a variable and when done moving all elements by 1, I would set the first element to the variable(Emily in this case).
How would I do it if having different increment values like 2, 3, 4, or even 6?
Edit: Any programming language is fine but it has to be done with for loops and no functions.
Update: I am an IGCSE student and this question is bugging from over a week.
If you can do an increment of one, just repeat that the required number of times.
A better way would be: (let's call the increment n); store the end n elements in another array; move the elements before that towards the end of the array; copy back the elements from the other array to the start. Like this:
Module Module1
Sub Main()
Dim players() As String = {"Adam", "Becky", "Clive", "Debby", "Edward", "Fiona"}
Dim rotateBy = 2
' make sure shiftBy is in a usable range
rotateBy = rotateBy Mod players.Length
' if shiftBy is negative, make it positive such that a left-rotate is performed
If rotateBy < 0 Then
rotateBy = rotateBy + players.Length
End If
' store the elements which will be moved to the other end of the array
Dim tmp(rotateBy - 1) As String
Dim startIndex = players.Length - rotateBy
For i = startIndex To players.Length - 1
tmp(i - startIndex) = players(i)
Next
' move the elements
For i = players.Length - 1 - rotateBy To 0 Step -1
players(i + rotateBy) = players(i)
Next
'fill in the other elements
For i = 0 To rotateBy - 1
players(i) = tmp(i)
Next
' show the result
Console.WriteLine(String.Join(", ", players))
Console.ReadLine()
End Sub
End Module
Note that the copying of elements within the players array is done backwards so that an overlapping range does not splat over values which have yet to be moved.
To shift the elements backwards, use a negative value for rotateBy.
If you are using a language with a function which gives array copying functions, this method is easy to adapt to use that functionality. For anyone wondering about that in the future:
Module Module1
Sub Main()
Dim players() As String = {"Adam", "Becky", "Clive", "Debby", "Edward", "Fiona"}
Dim rotateBy = 4
' make sure shiftBy is in a usable range
rotateBy = rotateBy Mod players.Length
' if shiftBy is negative, make it positive such that a left-rotate is performed
If rotateBy < 0 Then
rotateBy = rotateBy + players.Length
End If
' store the elements which will be moved to the other end of the array
Dim tmp(rotateBy - 1) As String
Dim startIndex = players.Length - rotateBy
Array.Copy(players, startIndex, tmp, 0, rotateBy)
Array.Copy(players, 0, players, rotateBy, startIndex)
Array.Copy(tmp, players, tmp.Length)
' show the result
Console.WriteLine(String.Join(", ", players))
Console.ReadLine()
End Sub
End Module
As you mentioned any programming language, this is what it could be in C# as a function but without using any framework methods such as Array.Copy:
public static void RotateUsingLoops<T>(T[] elements, int rotateBy)
{
rotateBy = rotateBy % elements.Length;
if (rotateBy < 0)
{
rotateBy += elements.Length;
}
T[] tmp = new T[rotateBy];
int startIndex = elements.Length - rotateBy;
// store the elements which will be moved to the other end of the array
for (int i = startIndex; i < elements.Length; i++)
{
tmp[i - startIndex] = elements[i];
}
// move the elements
for (int i = elements.Length - 1 - rotateBy; i >= 0; i--)
{
elements[i + rotateBy] = elements[i];
}
// fill in the other elements
for (int i = 0; i < rotateBy; i++)
{
elements[i] = tmp[i];
}
}
Whereby you could use
static void Main(string[] args)
{
var a = new string[] { "A", "B", "C", "D" };
RotateUsingLoops(a, 2);
Console.WriteLine(string.Join(", ", a));
Console.ReadLine();
}
to get an output of:
C, D, A, B
Circular array rotation is what you are referring towards.
In VB.NET the following code will rotate an array of elements to the Right, by the Shift amount.
Sub Main()
Dim Players() As String = {"Adam", "Helen", "Jack", "Emily"}
Dim Players_Shifted(Players.Length - 1) As String
Dim Shift As Integer = 2
If Shift > Players.Length Then
Shift = Shift Mod Players.Length
End If
For index = 0 To Shift - 1
Players_Shifted(index) = Players(Players.Length - Shift + index)
Next
Dim index_2 = 0
For index = Shift To Players.Length - 1
Players_Shifted(index) = Players(index_2)
index_2 = index_2 + 1
Next
Players = Players_Shifted
' Print out Players Array '
For index = 0 To Players.Length - 1
Console.Write(Players(index) + ", ")
Next
Console.ReadLine()
End Sub
Here is a snippet of a C++ code that implements this functionality-
Let temp be a temporary variable, N be the size of the array, shift be the number of places u wanna shift and arr be the original array.
int temp = arr[0];
int i = 0;
while(True){
//swap(arr(i + shift)%N, temp);
swap_var = temp;
temp = arr[(i+shift)%N];
arr[(i+shift)%N] = swap_var;
i = (i+shift)%N;
if (i == 0){
break;
}
}
Edit: Using for loop.
int temp = arr[0]; //change int to the type of variable ur array is
int i =0;
for (int count = 0; count<N ; count++){
//swap(arr(i + shift)%N, temp);
swap_var = temp;
temp = arr[(i+shift)%N];
arr[(i+shift)%N] = swap_var;
i = (i+shift)%N;
}
LeetCode Easy 88 Merge Sorted Array
Question:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additionalelements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
I got an error which I have commented in my code. I have printed the index2 and index3, both they are zero.They should be legal. Why I got this error?
Any help, I appreciate it. Thank you so much for your time!
class Solution
{
func merge(inout nums1:[Int], _ m: Int, _ nums2:[Int], _ n: Int)
{
var index1 = m - 1
var index2 = n - 1
var index3 = m + n - 1
while index2 >= 0 && index1 >= 0
{
if nums1[index1] > nums2[index2]
{
nums1[index3] = nums1[index1]
index3 -= 1
index1 -= 1
}
else
{
nums1[index3] = nums2[index2]
index3 -= 1
index2 -= 1
}
}
while index2 >= 0
{
print(index2)
print(index3)
nums1[index3] = nums2[index2] // fatal error: Index out of range
index3 -= 1
index2 -= 1
}
}
}
let test1 = Solution()
var haha = [Int]()
haha = []
test1.merge(&haha,0, [1],1)
print(haha)
Your variable nums1 is a 0-element array. So there isn't space for you to make the assignment. That is, index3=0 and you're using that to point to the first element of nums1, but there is not first element.
If, for example, you change:
haha = []
to:
haha = [0]
then your the array nums1 will have a 0-th element inside the method.
What is the problem with the following function to receive and execute:
func FibFast(num: Int) -> Array<Int> {
var fib_arr = [Int](num)
if num < 1 {
fib_arr[0] = 0
return fib_arr
} else if num < 2 {
fib_arr[1] = 1
return fib_arr
}else {
for var i = 2; i < num; i++ {
fib_arr[i] = fib_arr[i-1] + fib_arr[i-2]
}
return fib_arr
}
}
when I am trying to receive the array like:
var newArray = FibFast(10)
it's producing a bad execution.
You are attempting to subscript the array with indexes that don't exist, similarly in your else case you are trying to subscript to an index of 2 when the array is empty.
the line var fib_arr = [Int]() creates an empty array on integers. when you use fib_arr[0] = 0 you are trying to assign the value at index 0 to have a value of 0 but no value currently exists. I would recommend using the append(_) method ie. fib_arr.append(0).
Also when you pass in a value of 10 or anything that is 2 or more as the num parameter your if-else if-else statement is executing the for loop where you are attempting to access the index of 0 and 1 which have not been set as the earlier statements were never executed as they were skipped by the if-else if-else block.
The for loop and assign the values with subscripts is very indicative of the fact that you've probably learnt a different language before swift. You should note that the classic c-style for loop you are trying to use will be removed from swift soon so its better to get in the habbit of no using it. Ive rewritten your code as close to the way you wrote yours, please don't hesitate to ask if you have any questions about it.
func fib(num: Int) -> [Int] {
var fib_arr = [Int]()
if num == 0 {
fib_arr.append(0)
} else if num == 1 {
fib_arr.append(0)
fib_arr.append(1)
} else {
fib_arr = [0, 1]
for i in 2..<num {
fib_arr.append(fib_arr[i - 1] + fib_arr[i - 2])
}
}
return fib_arr
}
The answer proposed by Blake Lockley can also be coded like this:
func FibFast(num: Int) -> Array<Int> {
var fib_arr = [Int]() // empty array
if num < 1 {
fib_arr += [0] // add element [0]
return fib_arr
} else if num < 2 {
fib_arr += [0] // add element [0]
fib_arr += [1] // add element [1]
return fib_arr
}else {
fib_arr = [0, 1] // init with [0, 1]
for var i = 2; i < num; i++ {
// add computed element
fib_arr += [fib_arr[i-1] + fib_arr[i-2]]
}
return fib_arr
}
}
var a = [1,2,3]
var b = [1,2,3]
var c = [1,2,3,4]
Each array inside take out a number of a three digits.
A total of 36 kinds of combination of the above.
I want to compute the position of the each combination.
[1,1,1] position is 1
[1,1,2] position is 2
[2,2,4] position is?
I want to ask how much the position of a combination of them, is there a specific formula?
Write three nested for loops. First one is for array a,second for b and third for c. That way you will first change the c for a new permutation than b, than a. Before going to for loop declare a variable called count which is 1. At the third loop increase that variable by one. Example:
int first,second,third,count=1;
for(int i=0;i<a.size();i++)
{
first=a[i];
for(int k=0;k<b.size();k++)
{
second=b[k];
for(int g=0;g<c.size();g++)
{
third=c[g];
count=count+1; //count++
}
}
}
This is written in C++. But you get the idea.You can put if statements inbetween to find the number of the permutation that you are looking for.
var a = [1,2,3];
var b = [1,2,3];
var c = [1,2,3,4];
var all = [a,b,c];
var allCount = [b.length * c.length, c.length, 0];
function getIndex(combo) {
var count = 0;
for (var i = 0; i < combo.length; i++) {
var pos = all[i].indexOf(combo[i]);
if (pos < 0) {
throw new Error(combo[i] + "Not effective elements");
}
count += allCount[i] * pos;
}
count += combo[combo.length - 1];
return count;
}
console.log("index of [2,2,4] is " + getIndex([2,2,4]));
console.log("index of [1,1,1] is " + getIndex([1,1,1]));
console.log("index of [3,3,4] is " + getIndex([3,3,4]));
console.log("index of [1,2,3] is " + getIndex([1,2,3]));
console.log("index of [3,2,1] is " + getIndex([3,2,1]));
The output:
index of [2,2,4] is 20
index of [1,1,1] is 1
index of [3,3,4] is 36
index of [1,2,3] is 7
index of [3,2,1] is 29