This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 10: Applied problem solving

Subscript to linear indices

face Josiah Wang

Assume you have a two-dimensional table.

A user gives you the number of rows R, number of columns C, and a two-dimensional index (r, c) that refers to a cell position, where r is a row index and c a column index.

Write a program to convert (r, c) to a single-dimensional index s, assuming row-major ordering (i.e. s is ordered from left to right, and then top to bottom). All indices start from 0. See the figure below for an illustration.

Convert subscripts to linear indices

More specifically, write a program that reads in the following integer inputs from the user:

  1. The number of rows in the table
  2. The number of columns in the table
  3. A row index
  4. A column index

The program should output the index s as described above.

For simplicity, you can assume that your user is well-behaved and will always enter valid numbers.

Hint: use input("Prompt message") to read in a str from the user, and convert this to an int with int().

Hint: You only need a single line equation to perform this conversion!

Hint: Think carefully about the relationship between s and r, c, R, and C.

Sample run #1:

Enter the number of rows: 3
Enter the number of columns: 4
Enter row index: 1 
Enter column index: 2
6

Sample run #2:

Enter the number of rows: 6
Enter the number of columns: 2
Enter row index: 5
Enter column index: 1
11