Ruby arrays and how to print them - arrays

There was a one-liner in Ruby I saw on this site and lost track of:
if I need to print the results of some action with integers:
print {|e| e = e * e}
but how do I let Ruby know e is, say, 1 to 10?

use parenthesis around your range
(1..10).map {|ele| ele + 3} // 1 to 10 including the last number
(1...10).map {|ele| ele + 3 } // 1 to 9 excluding the last number

It's not really clear what you want to do, but here's an input
(1..10).to_a
This gives you an array of numbers from 1 to 10.

Related

Print array elements in reverse order

The first line contains an integer N, (the size of our array).
The second line contains N space-separated integers describing array's(A's) elements.
I have tried the following, however I looked at the solution page. However I do not understand how this code works. Can someone please explain it to me. I am pretty new in this coding world.
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
input 1234
output 4 3 2 1
In Python3:
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print(" ".join(str(x) for x in arr[::-1]))
Input:
1 4 3 2
Output:
2 3 4 1
You are creating a list of integer values, by removing spaces and splitting the values at ' '. After obtaining the list of integers, you are iterating over the list and converting the ith element from the back (a negative value of index denotes element with ith index from right and it is 1 based) of arr back to string and printing the number.
Example:
arr = [1,2,3,4]
print(arr[1]) #prints 2 on the console, i.e 2nd element from the left.
print(arr[-1]) #prints 4 on the console, i.e 1st element from the right.
Let's take this code snippet
n = int(input())
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
for i in range(len(arr)):
print(str(arr[-i-1]), end = " ")
The method input() will take the user input from key board. int(input()) will convert the input into int, if the input is in string format. like "4" instead of 4. The input value stored into variable n.
The Array input will be like this "1 2 3 4". So, we need to separate the string with space delimiter.
The strip() method returns a copy of the string with both leading and trailing characters removed.
The split() method returns a list of strings after breaking the given string by the specified separator.Here the separator is space. So, split(' ')
input().strip().split(' ') will take "1 2 3 4" as input and the output is "1" "2" "3" "4".
Now we need to take each element after separated. And then covert into int and store into array.
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
arr_one is a variable, this variable stores each element after split. For each element, we converted it into int and then storing into a array arr.
In python, array index start from 0. If we want to access from last index in the array, the index will start from -1, -2, -3, and so on.
for i in range(len(arr)): The for loop will iterate from index 0 to length of the array. in this example, size is 4.
printing array elements from index -1. and the end argument is used to end the print statement with given character, here the end character is " ". So the output will be 4 3 2 1.
The above code can be rewritten as below with more readability.
if __name__ == '__main__':
n = int(input())
inp = input("Enter the numbers seperated by spaces:::")
inp = inp.strip() # To remove the leading and trailing spaces
array = []
for item in inp.split(' '): # Splitting the input with space and iterating over each element
array.append(int(item)) # converting the element into integer and appending it to the list
print(array[::-1]) # here -1 says to display the items in the reverse order. Look into list comprehension for more details
For more details on list slicing, look in the python documentation.
Try this!
if __name__ == '__main__':
n = int(input()) # input as int from stream
arr = [int(arr_one) for arr_one in input().strip().split(' ')]
"""
1. asking for input from user
2. strip() function removes leading and trailing characters.
3. split(' ') function split your input on space into list of characters
4. arr_one variable contains yours splited character and your iterating over it using for loop
5. int(arr_one) converts it into integer and [] is nothing just storing everything into another list.
6. In last you are assigning new list to arr variable
"""
for i in reversed(arr): # loop over list in reverse order with built in fucntion
print(i, end = " ") # printing whatever comes in i
It should work like this:
3 # your n
1 2 3 # your input
3 2 1 # output

Give array elements unique IDs

I am trying to multiply every element in an array by the next 12 elements:
array.each do |n|
a = array.index(n)
b = a + 12
product = 1
array[a..b].each { |i| product *= i }
highest = product if product > highest
end
I run into a problem when there are multiple occurrences of the same integer in the array:
[1, 2, 3, 7, 5, 4, 7] # this is not the actual array
When the second 7 runs through my block, its array.index(n) becomes 3 (the index of the first 7) when I want it to be 6 (the index of the particular 7 I am working with). I'm pretty sure this can be solved by giving each element of the array a unique 'id', but I'm not sure how I would go about doing this.
My question is, how do I give every element in an array a unique id? The Array#uniq method is not what I am looking for.
you could simplify your code a little
highest = array.map.with_index do |item, i|
array[i, 13].inject(:*)
end.max
# printing it console
puts highest
or use array.max_by with explicit i counter
The index is the uniq id. Use Enumerable#each_with_index instead:
array.each_with_index do |n, a|
#...
end
Ruby has an each_cons method defined on Enumerable.each_consis short for each_consecutive.
array.each_cons(13).max_by{|slice| slice.inject(:*)}
For more efficiency consider determining the product of the first thirteen numbers; then going through the array multiplying the product by the next number and dividing it by the previous first, while keeping track of the maximum product.

Arrays from nested for loops in maxima

Using MAxima I want to create 11 arrays in maxima. I am trying something like this:
for n:1 step 1 while n<=11 do( for j:1 while j<=21 do( if i<j then aa[n][i,j]:i+j+n));
This compiles fine but I can not use it how I would like. Say for example I want value 2,2 in the 5th array, I try the following but it does not work:
aa[5][2,2];
Any help is appreciated,
Ben
Your code fragment is missing any loop over i or other assignment to i.
You might consider using 'genmatrix' to construct a matrix, and then a loop over n to generate several matrices. E.g.:
foo : lambda ([i, j], if i < j then i + j + n else 0);
for n:1 thru 11 do aa[n] : genmatrix (foo, 21, 21);
Then I get
aa[5][2, 2];
=> 0
aa[5][2, 3];
=> 10
grind (aa[10]);
=> matrix([0,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],
[0,0,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],
[0,0,0,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34],
[0,0,0,0,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],
[0,0,0,0,0,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36],
[0,0,0,0,0,0,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],
[0,0,0,0,0,0,0,25,26,27,28,29,30,31,32,33,34,35,36,37,38],
[0,0,0,0,0,0,0,0,27,28,29,30,31,32,33,34,35,36,37,38,39],
[0,0,0,0,0,0,0,0,0,29,30,31,32,33,34,35,36,37,38,39,40],
[0,0,0,0,0,0,0,0,0,0,31,32,33,34,35,36,37,38,39,40,41],
[0,0,0,0,0,0,0,0,0,0,0,33,34,35,36,37,38,39,40,41,42],
[0,0,0,0,0,0,0,0,0,0,0,0,35,36,37,38,39,40,41,42,43],
[0,0,0,0,0,0,0,0,0,0,0,0,0,37,38,39,40,41,42,43,44],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,39,40,41,42,43,44,45],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,41,42,43,44,45,46],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,43,44,45,46,47],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,45,46,47,48],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,47,48,49],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,49,50],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,51],
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])$

Multiple assignment in Scala without using Array?

I have an input something like this: "1 2 3 4 5".
What I would like to do, is to create a set of new variables, let a be the first one of the sequence, b the second, and xs the rest as a sequence (obviously I can do it in 3 different lines, but I would like to use multiple assignment).
A bit of search helped me by finding the right-ignoring sequence patterns, which I was able to use:
val Array(a, b, xs # _*) = "1 2 3 4 5".split(" ")
What I do not understand is that why doesn't it work if I try it with a tuple? I get an error for this:
val (a, b, xs # _*) = "1 2 3 4 5".split(" ")
The error message is:
<console>:1: error: illegal start of simple pattern
Are there any alternatives for multiple-assignment without using Array?
I have just started playing with Scala a few days ago, so please bear with me :-) Thanks in advance!
Other answers tell you why you can't use tuples, but arrays are awkward for this purpose. I prefer lists:
val a :: b :: xs = "1 2 3 4 5".split(" ").toList
Simple answer
val Array(a, b, xs # _*) = "1 2 3 4 5".split(" ")
The syntax you are seeing here is a simple pattern-match. It works because "1 2 3 4 5".split(" ") evaluates to an Array:
scala> "1 2 3 4 5".split(" ")
res0: Array[java.lang.String] = Array(1, 2, 3, 4, 5)
Since the right-hand-side is an Array, the pattern on the left-hand-size must, also, be an Array
The left-hand-side can be a tuple only if the right-hand-size evaluates to a tuple as well:
val (a, b, xs) = (1, 2, Seq(3,4,5))
More complex answer
Technically what's happening here is that the pattern match syntax is invoking the unapply method on the Array object, which looks like this:
def unapplySeq[T](x: Array[T]): Option[IndexedSeq[T]] =
if (x == null) None else Some(x.toIndexedSeq)
Note that the method accepts an Array. This is what Scala must see on the right-hand-size of the assignment. And it returns a Seq, which allows for the #_* syntax you used.
Your version with the tuple doesn't work because Tuple3's unapplySeq is defined with a Product3 as its parameter, not an Array:
def unapply[T1, T2, T3](x: Product3[T1, T2, T3]): Option[Product3[T1, T2, T3]] =
Some(x)
You can actually "extractors" like this that do whatever you want by simply creating an object and writing an unapply or unapplySeq method.
The answer is:
val a :: b :: c = "1 2 3 4 5".split(" ").toList
Should clarify that in some cases one may want to bind just the first n elements in a list, ignoring the non-matched elements. To do that, just add a trailing underscore:
val a :: b :: c :: _ = "1 2 3 4 5".split(" ").toList
That way:
c = "3" vs. c = List("3","4","5")
I'm not an expert in Scala by any means, but I think this might have to do with the fact that Tuples in Scala are just syntatic sugar for classes ranging from Tuple2 to Tuple22.
Meaning, Tuples in Scala aren't flexible structures like in Python or other languages of the sort, so it can't really create a Tuple with an unknown a priori size.
We can use pattern matching to extract the values from string and assign it to multiple variables. This requires two lines though.
Pattern says that there are 3 numbers([0-9]) with space in between. After the 3rd number, there can be text or not, which we don't care about (.*).
val pat = "([0-9]) ([0-9]) ([0-9]).*".r
val (a,b,c) = "1 2 3 4 5" match { case pat(a,b,c) => (a,b,c) }
Output
a: String = 1
b: String = 2
c: String = 3

How can I delete elements from a Perl array?

I have a pretty big array and I want to delete the 2nd, 8th, 14th etc. element from an array. My array currently is like this:
Element1 x A B C
Element 2 y A B C
Element 3 z A B C
Broadly, I want to delete the x, y and z (just as an example, my array is slighly more complex). And pull up the rest. As in, I don't want to have a blank space in their positions. I want to get:
Element 1 A B C
Element 2 A B C
Element 3 A B C
I tried to give this a try with my array "todelete":
print "#Before Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];
for ($count=2; $count<#todelete;
$count=$count+6) { delete
$todelete[$count]; }
print "#After Deleting"; print
$todelete[0]; print "\n"; print
$todelete[2]; print "\n"; print
$todelete[3];$todelete[3];
But, currently, I think it just unitializes my value, because when I print the result, it tells me:
Use of uninitialized value in print
Suggestions?
The function you want is splice.
delete $array[$index] is the same as calling $array[$index] = undef; it leaves a blank space in your array. For your specific problem, how about something like
#array = #array[ grep { $_ % 6 != 2 } 0 .. $#array ];
You can also use grep as a filter:
my $cnt = 0;
#todelete = grep { ++$cnt % 6 != 2 } #todelete;

Resources