how to output on ruby, two input in one single line - arrays

I need output two different array (or range ) which both of them takes by gets.chomp, one of them a string, the other must be integer. But i dont want to transpoze or i dont want to use zip method. because when i take output one of them in a row, the other might be reverse two or more times.
name = $name
num = $num
arr = $arr
puts "num?"
num = gets.chomp.to_i
arr = []
for x in (1..num)
puts "#{x}. name? " #its can be "A" ,"B","C"
name = gets.chomp.to_sym
arr.push (name)
end
for y in (1..100)
arr.each do |z|
print y, " " , z, "\n"
end
end
# i want to outputs like this :
1 A
2 B
3 C
4 A
5 B #reverse time (%5 == 0)
6 A
7 C
8 B
9 A
10 C #reverse time (%5 ==0)
11 A
integers dont reverse anytime, but Strings must be reverse...
Thanks for help..

Rather than using a nested loop, you want to pair your integer Range with your name Array, and then loop over the resulting Array of Arrays. In Ruby we can do this using the #zip method. Also, because the name array may not fill up the entire Range, we can #cycle the name array to convert it to a repeating Enumerator (otherwise, in the example given, 3 through 5 would be paired with nil).
>> arr = ["John", "Jane"]
>> pairs = (1..5).zip(arr.cycle)
#> [[1, "John"], [2, "Jane"], [3, "John"], [4, "Jane"], [5, "John"]]
>> pairs.each { |integer, name| print "#{integer} #{name}\n" }
1 John
2 Jane
3 John
4 Jane
5 John

Related

Randomly split array using split() and sample() in R

i have created an array consisting of N values, say
a <- array(dim = c(x, y)).
I want to partition the array into K groups, where array values are randomly assigned to one of K groups. For example if K = 2 and N = 10, one subarray could have 7 values while the other would have 3. The values in all subarrays must sum to N (e.g., 7 + 3 = 10).
I know using split() and sample() is probably the easiest route. I have tried
split(a, sample(a, 2))
but this does not work as it should.
Any ideas?
a <- array(c(1,2,3,4,5,6))
k <- 3
split(sample(a),1:k)
# [1] 2 3
#
# $`2`
# [1] 4 5
#
# $`3`
# [1] 6 1

ruby even Fibonacci numbers

I am a extreme newbie to coding, I am trying to find anything I can to practice on. This is one of the questions on the Euler test. This is what I came up with to get the answer, but I know it can be shortened. I am working with ruby. I have 2 questions.
1) what should I do to clean this up?
2) At the end I just had it pull the evens out and sum them. What I wanted to do was make an array of the numbers then search the array for the even answers then sum them. How can I make the result populate an array?
I know this is a simple thing that I am missing and I am sorry to bug you guys with such a newby thing.
1 bob=0
2 x = 0
3 y = 1
4 index = 0
5 while index < 4000000
6 z = (x+y)
7 x = y
8 y = z
9
10 index = y
11
12 if z.even?
13 bob = bob+z
14 end
15 end
16 p bob
Create an array
array = []
Append elements to it
array << element
Filter it using select
array = array.select { |each| each.even? }
Sum all elements using inject
sum = array.inject { |a, b| a + b }
Best read the documentation of Enumerable module to learn about all of Ruby's array methods.
Some of the most useful functions are
all?
any?
collect
each_cons
each_slice
detect
inject
none?
select
take
Have fun with Euler project!
BTW, you can use methods chaining to simplify the code. Like this:
(1..10).select(&:even?).inject(:+)
(1..10) represents numbers range.
Take a look also at:
Select method
Inject method
This is probably best handled by an Enumerator Docs. I would proceed as follows:
fib_only_evens = Enumerator.new do |y|
a,b =0,1
loop do
y << a if a.even?
a, b = b, a + b
end
end
Then you can retrieve the number of even Fibonacci numbers that you want by using Enumberable#first or #take
fib_only_evens.first(10)
#=> [0, 2, 8, 34, 144, 610, 2584, 10946, 46368, 196418]
fib_only_evens.take(20)
#=> [0, 2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578,
14930352, 63245986, 267914296, 1134903170, 4807526976, 20365011074,
86267571272, 365435296162]
Then using Enumerable#reduce to sum them
fib_only_evens.first(10).reduce(:+)
#=> 257114

Printing array of multi-digit elements in reverse order in ruby

How to print an array of elements in reverse order not just single digit number but also multi-digit numbers.
[2, 5, 6 7]
It should print the array elements in reverse order as 7 6 5 2 by following a space for each number.
I already wrote the code for this.
puts "Enter the array elements"
arr = gets.strip
arr = arr.split(' ').map(&:to_i)
x = arr.reverse_each {|f| }
z = x.join(" ")
print z.reverse
That is cool with single digit numbers, how can I reverse the multi-digit numbers in an array of inputs given by the user input like:
[45, 76, 87 ] # this should reverse the array as `87 76 45`
[556, 674, 878 ] # this should reverse the array as `878 674 556`
[8797, 7347, 9374 ] # this should reverse the array as `9374 7374 8797`
If you like one-liners:
gets.strip.split(' ').reverse.join(' ')
This will take the input 1 2 3 45 678 9 and convert it to "9 678 45 3 2 1"
Input: [8797, 7347, 9374 ]
Output: "9374 7374 8797"
arr = gets.chomp
arr = arr.split(' ').map(&:to_i)
x = arr.reverse.join(' ')
print x
Use reverse and join chained and it should return a String type that joined your reversed array.

how to convert a number array to a single string in matlab

How can i convert a numeric array to a single string, where array numbers will be separated with a comma ?
(e.g. convert A=[1 2 3] to a string '1,2,3')
Moreover, is there any way to apply the same above in case that matrix A contains variables in a for loop?
(e.g.
for i=1,10
A(i)=[1 1 i+1];
end
As variable i varies, I need to obtain a string '1,1,i+1'
thanks a lot !
There is a num2str() function
>> test =[123 124 125] % 3 element vector
test =
123 124 125
>> num2str(test) % 1 element string
ans =
123 124 125
and also a function to write ASCII delimited files
the process can easily be reversed with the str2num function, as dan pointed out
I think you need this:
for i=1:10
disp(['1,1,',num2str(i+1)])
end
Note: Try to avoid 'i' as the iteration variable.
The output:
1,1,2
1,1,3
1,1,4
1,1,5
1,1,6
1,1,7
1,1,8
1,1,9
1,1,10
1,1,11
for i=1:10
s = sprintf('%d,', A);
S{i} = s(1:end-1);
end
The function mat2str does just that:
>> A = [1 2 3];
>> mat2str(A)
ans =
[1 2 3]

Create all possible Mx1 vectors from an Nx1 vector in MATLAB

I am trying to create all possible 1xM vectors (word) from a 1xN vector (alphabet) in MATLAB. N is > M. For example, I want to create all possible 2x1 "words" from a 4x1 "alphabet" alphabet = [1 2 3 4];
I expect a result like:
[1 1]
[1 2]
[1 3]
[1 4]
[2 1]
[2 2]
...
I want to make M an input to my routine and I do not know it beforehand. Otherwise, I could easily do this using nested for-loops. Anyway to do this?
Try
[d1 d2] = ndgrid(alphabet);
[d2(:) d1(:)]
To parameterize on M:
d = cell(M, 1);
[d{:}] = ndgrid(alphabet);
for i = 1:M
d{i} = d{i}(:);
end
[d{end:-1:1}]
In general, and in languages that don't have ndgrid in their library, the way to parameterize for-loop nesting is using recursion.
[result] = function cartesian(alphabet, M)
if M <= 1
result = alphabet;
else
recursed = cartesian(alphabet, M-1)
N = size(recursed,1);
result = zeros(M, N * numel(alphabet));
for i=1:numel(alphabet)
result(1,1+(i-1)*N:i*N) = alphabet(i);
result(2:M,1+(i-1)*N:i*N) = recursed; % in MATLAB, this line can be vectorized with repmat... but in MATLAB you'd use ndgrid anyway
end
end
end
To get all k-letter combinations from an arbitrary alphabet, use
n = length(alphabet);
aux = dec2base(0:n^k-1,n)
aux2 = aux-'A';
ind = aux2<0;
aux2(ind) = aux(ind)-'0'
aux2(~ind) = aux2(~ind)+10;
words = alphabet(aux2+1)
The alphabet may consist of up to 36 elements (as per dec2base). Those elements may be numbers or characters.
How this works:
The numbers 0, 1, ... , n^k-1 when expressed in base n give all groups of k numbers taken from 0,...,n-1. dec2base does the conversion to base n, but gives the result in form of strings, so need to convert to the corresponding number (that's part with aux and aux2). We then add 1 to make the numbers 1,..., n. Finally, we index alphabet with that to use the real letters of numbers of the alphabet.
Example with letters:
>> alphabet = 'abc';
>> k = 2;
>> words
words =
aa
ab
ac
ba
bb
bc
ca
cb
cc
Example with numbers:
>> alphabet = [1 3 5 7];
>> k = 2;
>> words
words =
1 1
1 3
1 5
1 7
3 1
3 3
3 5
3 7
5 1
5 3
5 5
5 7
7 1
7 3
7 5
7 7
use ndgrid function in Matlab
[a,b] = ndgrid(alphabet)

Resources