JoshCheek's ruby-kickstart Challenge 1 Session 2 - arrays

As part of an exercises, I should write a program that reads in two integers typed on the keyboard, and then outputs their sum, difference, and product.
Standard input is like "9 2\n" and expects me to print "11\n7\n18\n" to standard output.
Am I getting it completely wrong?
def sum_difference_product
input = gets.chomp
array = input.split(" ").map { |x| x.to_i }
sum = array[0] + array[1]
difference = array[0] - array[1]
product = array[0] * array[1]
result = ""
result << sum
result << difference
result << product
return result
end
sum_difference_product

You're currently appending integers to a string using << which (from the looks of it) treats the int as raw binary. 1 for example becoms \u0001.
Instead change result to an array and join it using " " like this.
def sum_difference_product
input = gets.chomp
array = input.split(" ").map { |x| x.to_i }
pp array
sum = array.fetch(0) + array.fetch(1)
difference = array[0] - array[1]
product = array[0] * array[1]
result = []
result << sum
result << difference
result << product
return result.join(" ")
end
puts sum_difference_product

Okay, I was overcomplicating things... Removed result, sum, difference, product and just puts the parts that were in sum, difference and product. It's ok now:
def sum_difference_product
input = gets.chomp
array = input.split(" ").map { |x| x.to_i }
puts array[0] + array[1]
puts array[0] - array[1]
puts array[0] * array[1]
end

Related

Get the sum of numbers in a for loop

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

Finding the sum of nearest smallest and greatest number in an array

The question is straightforward that we want to find the sum of the nearest smallest and greatest number for every index of an array. But the part which I am not able to get is how to return the resulting array with the sum values on the same index values as the numbers.
Example: [1,5,2,3,8]
The sum for each indexes is as follows:
for index 0 the element is 1 hence sum = (0 + 2) = 2
since it has no smallest number therefore taking the nearest smallest number to be 0.
similarly for index 1 sum = (3 + 8 ) = 11 {3 - nearest smallest number to 5 and 8 nearest largest number}
and so on.
What I did was sort the given array then iterate through it and in every iteration take the sum of arr[i-1] + arr[i+1] elements and storing them in the result/answer array.{ with 0th and last element being dealt with separately }
So basically
If the input array is -> [1,5,2,3,8]
the resultant array will be -> [2,4,7,11,5]
but it is required to be as -> [2,11,4,7,5]
that is the sum of each index element to be at the same index as was the initial number
(I am using C++)
You will get the desired output by running this. It is written in Go.
Copy the original input array
Sort the copied array
Create a Map Sorted Value -> Sorted Index
make an output array with same length as input
Iterate through the Input Array and check the value is largest or smallest and Do the Sum as described in the question
store the Sum in the output array in the same index as input array
package main
import (
"fmt"
"sort"
)
func main() {
indexes := []int{1, 5, 2, 3, 8}
output := findSum(indexes)
fmt.Println(output)
}
func findSum(input []int) []int {
if len(input) < 2 {
return input
}
sorted := make([]int, len(input))
copy(sorted, input)
sort.Slice(sorted, func(i, j int) bool {
return sorted[i]< sorted[j]
})
sortedMap := make(map[int]int)
for i, i2 := range sorted {
sortedMap[i2] = i
}
output := make([]int, len(input))
for j, index := range input {
i := sortedMap[index]
if i == 0 {
output[j] = sorted[i+1]
continue
}
if i == len(input) - 1 {
output[j] = sorted[i-1]
continue
}
output[j] = sorted[i - 1] + sorted[i + 1]
}
return output
}
You can run here
The trick is to create an array of indexes into the original array and sort this, rather than sorting the original array.
You don't mention what language you're using, but here's some Java code to illustrate:
Integer[] arr = {1,5,2,3,8};
System.out.println(Arrays.toString(arr));
Integer[] idx = new Integer[arr.length];
for(int i=0; i<idx.length; i++) idx[i] = i;
System.out.println(Arrays.toString(idx));
Arrays.sort(idx, (a, b) -> arr[a] - arr[b]);
System.out.println(Arrays.toString(idx));
Integer[] res = new Integer[arr.length];
for(int i=0; i<arr.length; i++)
{
res[idx[i]] = (i > 0 ? arr[idx[i-1]] : 0) + (i < arr.length - 1 ? arr[idx[i+1]] : 0);
}
System.out.println(Arrays.toString(res));
Or translated into (possibly non-idiomatic) C++ (Ideone):
int len = 5;
array<int, 5> arr{1,5,2,3,8};
for(auto i : arr) cout << i << " ";
cout << endl;
array<int, 5> idx;
for(int i=0; i<len; i++) idx[i] = i;
for(auto i : idx) cout << i << " ";
cout << endl;
sort(idx.begin(), idx.end(), [&arr](int a, int b) {return arr[a] < arr[b];});
for(auto i : idx) cout << i << " ";
cout << endl;
array<int, 5> res;
for(int i=0; i<len; i++)
res[idx[i]] = (i > 0 ? arr[idx[i-1]] : 0) + (i < len - 1 ? arr[idx[i+1]] : 0);
for(auto i : res) cout << i << " ";
cout << endl;
Output:
[1, 5, 2, 3, 8]
[0, 1, 2, 3, 4]
[0, 2, 3, 1, 4]
[2, 11, 4, 7, 5]

How do you print an array if it has more than 2 index?

Here is my code when i printed it, the print would not show the expected result and I tried making the array into string but the result lead to printing a boxes.
c=0;
array1=[];
for r=1:1
while c<=5
value = "Enter value for index " + c + ":";
array1(r,c+1)=input(value);
c=c+1;
end
end
[maxval]= max(array1);
[index1] = find(ismember(array1, max(array1(:))));
[minval]= min(array1);
[index2] = find(ismember(array1, min(array1(:))));
fprintf("The highest value is %d located in index %d.\n", maxval,index1)
fprintf("The lowest value is %d located in index %d.", minval,index2)
MATLAB follows a base-1 indexing scheme, but if you insist on using a base-0 indexing approach you can offset the values retrieved by the ismember() function by subtracting 1. Below I added some pre-allocation to the array size and reduced the script to include only the while-loop.
clc;
c = 1;
Array_Size = 6;
array1 = zeros(1,Array_Size);
while c <= Array_Size
value = "Enter value for index " + num2str(c-1) + ": ";
array1(c)=input(value);
c=c+1;
end
[maxval] = max(array1);
[index1] = find(ismember(array1, max(array1)));
[minval] = min(array1);
[index2] = find(ismember(array1, min(array1)));
index1 = index1 - 1;
index2 = index2 - 1;
fprintf("The highest value is %d located in index %d.\n", maxval,index1);
fprintf("The lowest value is %d located in index %d.\n", minval,index2);

How to make a parent thread output global variables defined in worker threads

The following is a multi-threaded program that does simple statistical computations on a user-defined array, I can't seem to figure out how to make the parent thread output the global variables defined in the worker threads, also how do I make a function that is invoked by using start() on a thread that points to that function to return a value?
import threading as th
# Function to give maximum in array
def maximum(arr):
global maxi
maxi = 0
for x in range(len(arr)):
if arr[x] > maxi:
maxi = arr[x]
#print ("%sMaximum value is: %s " % (" " , max) + "\n")
# Function to give minimum in array
def minimum(arr):
global mini
mini = 999999
for x in range(len(arr)):
if arr[x] < mini:
mini = arr[x]
#print ("%sMinimum value is: %s " % (" " , min) + "\n")
# Function to give average of an array
def average(arr):
count = len(arr)
global summ
summ = 0
for x in range(count):
summ = summ + arr[x]
avg = summ / count
#print ("%sAverage value is: %s " % (" " , avg) + "\n")
# Function to prompt user to input array of numbers
def defArray():
array = []
n = int(input("Please Enter the size of your Array of numbers: "))
for x in range(n):
s = input("Please Enter a number: ")
if check(s) == False:
print("Invalid User Input, Please make sure input is a number")
return
else:
array.append(float(s))
print("Your array is: ")
print(array)
return array
# Function to check if user input is correct
def check(item):
user_number = str(item)
if( user_number.isdigit()):
return True
else:
return False
# Section for calling the previous function to show execution
array = defArray()
t1 = th.Thread(target=maximum,args=[array])
t2 = th.Thread(target=minimum,args=[array])
t3 = th.Thread(target=average,args=[array])
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()

Each array to come up with a number, calculate out the location of the array

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

Resources